1

I'm working in Swift UI 2.0 and currently have a setup as follows:

@main
struct MyApp: App {
    @Environment(\.scenePhase) private var scenePhase
    var body: some Scene {
        WindowGroup {
           InitialView()
        }
        .onChange(of: scenePhase) { (newScenePhase) in
            switch newScenePhase {
            case .active:
                print("scene is now active!")
            case .inactive:
                print("scene is now inactive!")
            case .background:
                print("scene is now in the background!")
                
            @unknown default:
                print("sus")
            }
        }
    }
}

which is fine but none of these account for the case when the application is terminated (i.e. a user double taps the home button and swipes up on the app). How can I account for this case?

I tried unsuccessfully implementing applicationWillTerminate(_:) so any guidance here would be appreciated.

Thank you!

Evan
  • 1,892
  • 2
  • 19
  • 40

1 Answers1

0

Here is something I grabbed from a previous project. You can setup a notification observer to check if the app has "moved to background", so basically when the user exits the app.

 init() {
        let notificationCenter = NotificationCenter.default
            notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
    }

Just throw that in your main viewcontroller's init method and...

@objc func appMovedToBackground() {
    print("App moved to background")
}
kevincrab
  • 74
  • 1
  • 7
  • hi, thanks for the answer but this is just similar to the .inactive case in that we're detecting when the app moved to the background but not when the app was terminated. I guess apple's philosophy here is that you should save all your user data/clean up as soon as the app moves to the background and not when it's terminated. – Evan Jan 28 '21 at 05:14