8

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.

alexbayker
  • 882
  • 9
  • 19
  • 2
    I refer to beta software, so I am not allowed to provide any information on SO, but if you're using the new `App` and `Scene` protocols with `WindowGroup` container, then it is as presented in this Apple Developer Forum question titled ["Using Core Data with SwiftUI App Protocol"](https://developer.apple.com/forums/thread/650876) and [my answer](https://developer.apple.com/forums/thread/650876?answerId=620207022#620207022) – andrewbuilder Sep 10 '20 at 12:03

3 Answers3

12

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:

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • 4
    This also works with `NSApplication.willTerminateNotification` if you are writing a Mac app. – citelao Dec 19 '20 at 16:33
  • I had a hard time implementing an async func it looks like we only have about 5 seconds to do whatever we need and return. https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623111-applicationwillterminate – Andy Oct 15 '22 at 16:50
9

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:

Deitsch
  • 1,610
  • 14
  • 28
Alhomaidhi
  • 517
  • 4
  • 12
  • This does **not** get called on a view inside a `WindowGroup`, `WindowGroup { ContentView(). onReceive ...` – bauerMusic Sep 02 '23 at 03:46
1

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")
   }
zdravko zdravkin
  • 2,090
  • 19
  • 21