我认为注册推送通知的正确方法是先配置用户交互,然后注册推送通知,如下所示
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()
}
}但是apple展示了不同的方式,它不建议在配置用户交互后注册远程通知作为回调,而是要求配置用户交互,然后注册推送通知,而不等待用户响应,正如您看到的here
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Configure the user interactions first.
self.configureUserInteractions()
NSApplication.shared().registerForRemoteNotifications(matching: [.alert, .sound])
}哪种方法是正确的?
发布于 2016-12-12 19:26:13
如果您对 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)")
}发布于 2016-12-12 18:08:08
这不是对错的问题,更像是旧的和新的。苹果将远程和本地通知的接收合并到applicationDidFinishLaunching中,因此如果您处理它们的代码相似,则会减少重复代码。您可以观看this video from Apple并了解其中的变化。
但请注意,如果您的应用程序支持iOS 10.0之前的版本,这些新方法中的一些可能不起作用。确保你的应用程序在这种情况下仍然可以处理旧方法-或者只使用旧方法,直到你的应用程序在iOS 10.0和更高版本上运行。
https://stackoverflow.com/questions/41098082
复制相似问题