应用程序终止时推送通知

5
我的应用程序在后台和/或前台使用推送通知正常工作。
我遇到的问题是如果应用程序被终止(我通过双击主屏幕按钮找到应用程序并向上滑动来强制终止应用程序)。
我正在使用iOS 9和Swift 2。
在AppDelegate的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) {...}

根据文档和此链接,与旧版本的didReceiveRemoteNotification相反,如果应用程序被终止(而不是调用will/did finishLaunchingWithOptions),则会调用此方法。
然而,如果有一个推送(已经收到 - 我可以在屏幕上看到它),并且在它被终止后启动应用程序,则似乎不会调用此方法,因为处理推送的代码(仅发布通知以便由相应的ViewController接收)不会被调用。
我错过了什么?我需要在didFinishLaunchingWithOptions中进行其他检查吗?还是其他地方?
1个回答

2

我成功解决了在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()

        }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接