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:
?