SwiftUI: respond to app termination on macOS

那年仲夏 提交于 2021-01-05 08:52:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!