2016-12-12 143 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)") 
}