我认为注册推送通知的正确方法是先配置用户交互然后注册推送通知,如下所示
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])
}
哪种方法是正确的?
最佳答案
如果您对 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)")
}
关于ios - 如何注册推送通知? iOS 10,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41098082/