应用程序终止时推送通知

时间:2015-12-19 02:05:25

标签: ios push-notification apple-push-notifications swift2

如果应用程序位于后台和/或应用程序位于前台,我的应用程序可以正常使用推送通知。

我遇到的问题是应用程序是否终止(双击主页按钮,找到应用程序,然后向上滑动)。

我正在使用ios 9和swift 2.

在app 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 / doneLaunchingWithOptions相反)。

但是,如果有一个推送(已经收到 - 我可以在屏幕上看到它)并且在终止后启动应用程序,这个方法似乎不会被称为处理推送的代码(只需发布一个通知,以便它被相应的ViewController拾取)不会被调用。

我错过了什么?我需要在didFinishLaunchingWithOptions中进行额外的检查吗?在其他地方?

1 个答案:

答案 0 :(得分: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()

        }

}
相关问题