这是一个陈旧的帖子……但是它仍然缺少解决该问题的实际方法(如各种注释中所指出的)。
最初的问题是关于从推送通知中检测应用程序何时启动
/ 打开的情况,例如,用户点击通知。答案实际上都没有涵盖这种情况。
通知到达时,可以在呼叫流程中看到原因, application:didReceiveRemoteNotification...
当接收到通知被调用和时再通知是由用户点击。因此,仅查看UIApplicationState
用户是否点击它就无法分辨。
此外,您不再需要处理应用程序“冷启动”的情况,application:didFinishLaunchingWithOptions...
就像application:didReceiveRemoteNotification...
在iOS 9+(也许还有8)中启动后再次被调用一样。
那么,如何判断用户是否点击了事件链?我的解决方案是标记应用开始从后台退出或冷启动的时间,然后在中检查该时间application:didReceiveRemoteNotification...
。如果小于0.1s,则可以确定点击是否触发了启动。
斯威夫特2.x
class AppDelegate: UIResponder, UIApplicationDelegate {
var wakeTime : NSDate = NSDate() // when did our application wake up most recently?
func applicationWillEnterForeground(application: UIApplication) {
// time stamp the entering of foreground so we can tell how we got here
wakeTime = NSDate()
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// ensure the userInfo dictionary has the data you expect
if let type = userInfo["type"] as? String where type == "status" {
// IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
if application.applicationState != UIApplicationState.Background && NSDate().timeIntervalSinceDate(wakeTime) < 0.1 {
// User Tap on notification Started the App
}
else {
// DO stuff here if you ONLY want it to happen when the push arrives
}
completionHandler(.NewData)
}
else {
completionHandler(.NoData)
}
}
}
迅捷3
class AppDelegate: UIResponder, UIApplicationDelegate {
var wakeTime : Date = Date() // when did our application wake up most recently?
func applicationWillEnterForeground(_ application: UIApplication) {
// time stamp the entering of foreground so we can tell how we got here
wakeTime = Date()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// ensure the userInfo dictionary has the data you expect
if let type = userInfo["type"] as? String, type == "status" {
// IF the wakeTime is less than 1/10 of a second, then we got here by tapping a notification
if application.applicationState != UIApplicationState.background && Date().timeIntervalSince(wakeTime) < 0.1 {
// User Tap on notification Started the App
}
else {
// DO stuff here if you ONLY want it to happen when the push arrives
}
completionHandler(.newData)
}
else {
completionHandler(.noData)
}
}
}
我已经在iOS 9+的两种情况下(在后台运行应用程序,未运行应用程序)都对此进行了测试,它的工作原理很吸引人。0.1s也很保守,实际值为〜0.002s,所以0.01也很好。