2016-12-12 49 views
1

我想爲推送通知登記正確的方法是先配置的用戶交互,然後註冊推送通知,如波紋管如何註冊推送通知? ios10

let center = UNUserNotificationCenter.current() 
       center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in 

        if granted { 

        // Register with APNs 
        UIApplication.shared.registerForRemoteNotifications() 

        }else{ 

         //user did't grant permissino: so we need to send phone ids, as we need to call this function every time the application opened 
         self.sendPhoneIdsToLookitServer() 


        } 


       } 

但蘋果表現出不同的方式,它不建議用於遠程寄存器通知作爲配置的用戶交互,而要求它配置的用戶交互,然後註冊推送通知,而無需等待用戶的響應,你可以看到here

func applicationDidFinishLaunching(_ aNotification: Notification) { 
    // Configure the user interactions first. 
    self.configureUserInteractions() 

    NSApplication.shared().registerForRemoteNotifications(matching: [.alert, .sound]) 
} 

哪一種方法是正確的後回調?

+0

這詳細解釋:HTTP ://stackoverflow.com/a/40430122/3882338 –

+0

@david,你可以看看下面我的答案 –

回答

0

這不是正確的錯誤,更像老的和更新的。 Apple將遠程和本地通知接收到applicationDidFinishLaunching中,所以如果你的代碼處理類似,那麼重複代碼會少一些。你可以看this video from Apple並瞭解變化。

但請注意,如果您的應用程序支持iOS 10.0之前的版本,則其中一些新方法可能無法使用。確保你的應用程序在這種情況下仍然可以處理舊的方法 - 或者直到你的應用程序在iOS 10.0及更高版本上運行,才使用舊的方法。

2

如果你是開放的超過UNUserNotificationCenter requestAuthorization其他不同的方法那麼這一定能夠解決您的問題,它也適用於iOS 9書面和8

func registerForNotification(application : UIApplication) { 

    if #available(iOS 10.0, *) { 
     let setting = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) 
     UIApplication.shared.registerUserNotificationSettings(setting) 
     UIApplication.shared.registerForRemoteNotifications() 
    } 
     // iOS 9 support 
    else if #available(iOS 9, *) { 
     UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) 
     UIApplication.shared.registerForRemoteNotifications() 
    } 
     // iOS 8 support 
    else if #available(iOS 8, *) { 
     UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)) 
     UIApplication.shared.registerForRemoteNotifications() 
    } 
} 

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) 
    print("deviceTokenString ======= \(deviceTokenString)") 
} 

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { 
    print("didFailToRegisterForRemoteNotificationsWithError \(error)") 
} 

func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) { 
    // Print notification payload data 
    print("Push notification received: \(data)") 
}