问题
I am creating a cross-platform app with SwiftUI 2.0. The app's lifecycle is managed by SwiftUI, so there is no app or scene delegate. If possible, I would like to keep it that way. In order to persist data when the app quits or enters the background, I am watching for changes on scenePhase.
@main
struct MyApp: App {
@Environment(\.scenePhase) var scenePhase
@StateObject var dataModel = DataModel()
var body: some Scene {
WindowGroup {
ContentView()
.onChange(of: scenePhase) { newScenePhase in
switch newScenePhase {
case .background, .inactive:
dataModel.save()
default: break
}
}
}
}
However, this approach has an inherent flaw: on macOS, when the app is terminated, there is no change in scenePhase, and thus the data is not persisted. Is there a separate mechanism for detecting app termination? Does SwiftUI have the equivalent of applicationWillTerminate:?
回答1:
You can inject application delegate via adapter. Use as the following example:
#if os(macOS)
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
#endif
@main
struct MyApp: App {
#if os(macOS)
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
// ... other code
}
来源:https://stackoverflow.com/questions/64940411/swiftui-respond-to-app-termination-on-macos