2015-12-19 72 views
6

如果應用程序在後臺和/或應用程序位於前臺,我的應用程序可以正常使用推送通知。應用程序終止時的推送通知

我的問題是,如果應用程序終止(我強制通過雙擊主頁按鈕,找到應用程序,並向上滑動)。

我使用的是iOS 9快捷2.

在應用程序的委託,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中執行額外的檢查?別的地方?

回答

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() 

     } 

}