How can I handle close and terminate app events in SwiftUI?
View
{
...
}.onDisappear {
//My code
}
Working only when I change view, not when I close or terminate my app.
How can I handle close and terminate app events in SwiftUI?
View
{
...
}.onDisappear {
//My code
}
Working only when I change view, not when I close or terminate my app.
You can use UIApplication.willTerminateNotification:
NotificationCenter.default.addObserver(forName: UIApplication.willTerminateNotification, object: nil, queue: .main) { _ in
// terminating
}
This answer may explain better how to use it in SwiftUI:
You should use .onReceive modifier and Subscribe to the notification you want like this:
YourView()
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification), perform: { output in
//Did enter background
})
You can use UIApplicationDelegate notifications and UIScene notifications
Docs: