【发布时间】:2018-08-08 09:57:18
【问题描述】:
我正在开发 SDK 并尝试捕获应用程序终止 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你可以找到:
调用此方法后,应用还会发布一个 UIApplicationWillTerminate 通知给感兴趣的对象一个 有机会响应过渡。
然而这似乎被打破了
【问题讨论】:
-
您预计何时收到通知?比较stackoverflow.com/questions/7417003/…。
-
这不是真的。有状态变化的通知。如果应用处于前台而不是挂起状态,则会调用 AppDelegate 中的
applicationWillTerminate。 -
根据Apple documentation,如果应用被用户杀死,则不会调用此函数:
For apps that support background execution, this method is generally not called when the user quits the app because the app simply moves to the background in that case. However, this method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason. -
@rckoenes @Martin R - 暂停/后台和活动状态之间存在巨大差异。看看这个:vimeo.com/257906400 你引用的文档@rckoenes 说:
this method is generally not called when the user quits the app because the app simply moves to the background所以它不是指终止用户,而是把它放在后台。这是 2 个不同的操作。 -
@rckoenes 看看我之前评论中的视频。我已经做到了(从应用切换器中杀死应用)并且它确实被调用了。