如果应用程序在后台和/或在前台,我的应用程序可以正常使用推送通知。
我遇到的问题是应用程序是否终止(我通过双击主页按钮强制终止,找到应用程序,然后向上滑动)。
我正在使用 ios 9 和 swift 2。
在应用程序委托(delegate)中,didFinishLaunchingWithOptions,我这样做:
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
然后:
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
application.registerForRemoteNotifications()
}
紧随其后的是 didRegisterForRemoteNotificationsWithDeviceToken & didFailToRegisterForRemoteNotificationsWithError。
然后,我使用比较新的方法:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {...}
根据文档和此 link ,与 didReceiveRemoteNotification
的旧版本相反,如果应用程序终止,则调用此方法(与调用 will/did finishLaunchingWithOptions 相反)。
但是,如果有推送(已收到 - 我可以在屏幕上看到它)并且我在应用程序终止后启动应用程序,则似乎不会调用此方法作为处理推送的代码(只需发布一个通知,以便它被相应的 ViewController 接收)不会被调用。
我错过了什么?我需要在 didFinishLaunchingWithOptions 中做额外的检查吗?其他地方?
最佳答案
设法解决了在 ios 9.1 上终止应用程序时拦截远程推送的问题,但它在 9.2 上失败(随机失败?):
远程注册:
if #available(iOS 9, *) {
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
// UIApplication.sharedApplication().registerUserNotificationSettings(settings)
//
// UIApplication.sharedApplication().registerForRemoteNotifications()
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
} else if #available(iOS 8.0, *){
register for 8...
} else { //ios 7
register for 7...
}
if let _ = launchOptions {
if let _ = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
handleRemotePush()
} else if let _ = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
handleLocalNots()
} else {
handleElse()
}
}
关于ios - 应用程序终止时推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34366510/