Search code examples
swiftevent-handlingswiftui

Handling close and terminate app events (SwiftUI)


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.


Solution

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