I have an application that runs in the background capturing the user's location using CoreLocation. I want to save the data when the app is closed by the user.
When the app goes to the background, I can use the scenePhase, but how to detect that the application will be terminated when it's running in the background?
import SwiftUI
@main
struct myApp: App {
@Environment(\.scenePhase) var scenePhase
var body: some Scene {
WindowGroup {
ContentView()
.onChange(of: scenePhase, perform: { phase in
print(scenePhase)
})
}
}
}
this prints:
inactive
background
I have also tried the NotificationCenter
NotificationCenter.default.addObserver(
forName: UIApplication.willTerminateNotification,
object: nil,
queue: .main)
{ _ in
print("terminated")
}
and this is also not called when the app is already in the background.