Observe App's Lifecycle in SwiftUI
Recently, I’m writing a pure SwiftUI MacOS application. But I found that there’s no app delegate in the App struct type. Sometimes we need to observe the lifecycle of the application. The SwiftUI provides two ways that we can observe the app’s lifecycle.
- Environment scenePhase
- The wrapped value NSApplicationDelegateAdaptor
1 | // ClassSchedulerApp.swift |
1 | // AppDelegator.swift |
Environment scenePhase
first, you should declare an Environment property scenePhase. And then, use the function onChange
to observer it. When the app is closed or minimized, the phase will be inactive
. If the app comes back to the foreground, the phase will be active
. You can look at the ScenePhase’s values in the Apple’s documents.
@NSApplicationDelegateAdaptor
The wrapped value @NSApplicationDelegateAdaptor
gives us a familiar way to observe the app’s lifecycle that to implement a class AppDelegator abiding by the protocol NSApplicationDelegate
. In the class AppDelegator, you can do anything you want just like in the UIKit
or AppKit
.