应用程序将终止通知

Jak*_*kub 5 ios swift

我正在开发 SDK 并尝试捕获应用程序终止Notification。很容易将其作为(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.
}
Run Code Online (Sandbox Code Playgroud)

所以我想有类似的终止行为:

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

而这个永远不会被调用!

当然,如果我输入AppDelegate

func applicationWillTerminate(_ application: UIApplication) {
    //termination
}
Run Code Online (Sandbox Code Playgroud)

它会工作,但由于我正在构建一个 SDK,我无法使用 AppDelegate 方法。有没有办法获得终止关闭调用?或者任何其他方式知道应用程序即将终止?

Apple 文档中,您可以找到:

调用此方法后,应用程序还会发布 UIApplicationWillTerminate 通知,让感兴趣的对象有机会响应转换。

然而这似乎被打破了

Swa*_*ain 8

这似乎对我有用:

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)
}
Run Code Online (Sandbox Code Playgroud)