Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

App will terminate Notification

Tags:

ios

swift

I'm working on SDK and try to catch app termination Notification. It's easy to get this as closure for (ex) NSNotification.Name.UIApplicationWillResignActive

self.resignActiveNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillResignActive,
                                                                       object: nil,
                                                                       queue: nil) { _ in
//something goes here and it works like a charm.
}

So I want to have similar behavior for termination:

self.terminateNotification = NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationWillTerminate,
                                                                    object: nil,
                                                                    queue: nil) { _ in
        NSLog("%@",#function)
    }

And this one never gets called!

Of course if I put in AppDelegate:

func applicationWillTerminate(_ application: UIApplication) {
    //termination
}

It will work, but since I'm building an SDK I cannot have AppDelegate methods. There is a way to get termination closure call? Or any other way to know that application is about to terminate?

In Apple documentation you can find:

After calling this method, the app also posts a UIApplicationWillTerminate notification to give interested objects a chance to respond to the transition.

However this seems to be broken

like image 768
Jakub Avatar asked Feb 28 '18 13:02

Jakub


1 Answers

This seems working for me:

init() {
  NotificationCenter.default.addObserver(self,
      selector: #selector(applicationWillTerminate(notification:)),
      name: UIApplication.willTerminateNotification,
      object: nil)
}

@objc func applicationWillTerminate(notification: Notification) {
  // Notification received.
}

deinit {
  NotificationCenter.default.removeObserver(self)
}
like image 162
Swapnil Jain Avatar answered Sep 30 '22 04:09

Swapnil Jain