我希望在app启动时调用一次didRegisterForRemoteNotificationsWithDeviceToken:
以响应推送通知注册。
但是,我注意到它被称为2次:一次推送通知注册成功,用户点击“允许访问”的其他时间!鉴于文件,后者不是预期的。
推送通知注册码:
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
仅在iOS 10中发生。我尝试在iOS 9上运行它并且不会在那里发生。
我确保不会多次调用registerForRemoteNotifications
。
一些观察(如预期的那样):
registerForRemoteNotifications
而不是registerUserNotificationSettings
时,didRegisterForRemoteNotificationsWithDeviceToken:
只会被调用一次。registerUserNotificationSettings
而非registerForRemoteNotifications
时,则根本不会调用didRegisterForRemoteNotificationsWithDeviceToken:
。 感谢您的帮助。
答案 0 :(得分:0)
为此你需要在应用程序中调用方法registerForRemoteNotifications didFinishLaunchingWithOptions launchOptions:
// Method For ReGister Notification
func registerUserNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
// Method For seeting if User Don;t allow For Remote Notification
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async(execute: {
UIApplication.shared.registerForRemoteNotifications()
})
}
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerUserNotifications()
return true
}