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:
NSApplication.willTerminateNotification
if you are writing a Mac app. –
Aide You should use .onReceive modifier and Subscribe to the notification you want like this:
YourView()
.onReceive(NotificationCenter.default.publisher(for: UIApplication.willTerminateNotification), perform: { output in
// Code to run on will terminate
})
You can use UIApplicationDelegate notifications and UIScene notifications
Docs:
WindowGroup
, WindowGroup { ContentView(). onReceive ...
–
Pettway NSApplication.willTerminateNotification
works on WindowGroup
, however at least 1 window instance needs to be still open for it to trigger. If all windows are clossed and the app is quit/terminated, it does not trigger. –
Meanie This work when you swipe up and close the app right away, but when you go to home screen and the close the app is not called.
class AppDelegate: NSObject, UIApplicationDelegate {
func applicationWillTerminate(_ application: UIApplication) {
print("End App")
}
© 2022 - 2024 — McMap. All rights reserved.
App
andScene
protocols withWindowGroup
container, then it is as presented in this Apple Developer Forum question titled "Using Core Data with SwiftUI App Protocol" and my answer – Drag