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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// ClassSchedulerApp.swift
@main
struct ClassSchedulerApp: App {

@Environment(\.scenePhase) private var scenePhase
@NSApplicationDelegateAdaptor(AppDelegator.self) var appDelegate

var body: some Scene {
WindowGroup {
RootView()
}
.onChange(of: scenePhase) { phase in
print(phase)
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
// AppDelegator.swift
class AppDelegator: NSObject, NSApplicationDelegate {

func applicationWillFinishLaunching(_ notification: Notification) {
print("applicationWillFinishLaunching")
}

func applicationDidFinishLaunching(_ notification: Notification) {
print("applicationDidFinishLaunching")
}
}

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.