OGeek|极客世界-中国程序员成长平台

标题: ios - 应用程序将终止通知 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:48
标题: ios - 应用程序将终止通知

我正在开发 SDK 并 try catch 应用程序终止 Notification。很容易将其作为(例如)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.
}

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

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

而且这个永远不会被调用!

当然,如果我输入 AppDelegate:

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

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

Apple documentation你可以找到:

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

然而这似乎被打破了



Best Answer-推荐答案


这似乎对我有用:

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)
}

关于ios - 应用程序将终止通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49030947/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4