在 iOS 10 之前,我可以注册并接收通知。现在我没有收到。这是我的代码:
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if error == nil {
if granted {
print("granted")
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
} else {
print("not granted")
}
} else {
}
}
} else {
// Fallback on earlier versions
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [UIUserNotificationType.badge, UIUserNotificationType.sound, UIUserNotificationType.alert], categories: nil)
UIApplication.shared.registerForRemoteNotifications()
UIApplication.shared.registerUserNotificationSettings(settings)
}
顺便说一下,granted
有时是真的,有时是假的。我没有收到任何通知。回调与通知工作时的回调相同。
最佳答案
你的代码似乎是正确的,但你可以尝试这样的事情。
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) {[weak self] (granted, error) in
guard error == nil else { return }
if granted {
// register for remote notifications
UIApplication.shared.registerForRemoteNotifications()
// set delegate
UNUserNotificationCenter.current().delegate = self
}
}
您将通过以下方法收到 iOS 10 的通知。
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound, .badge])
}
当您点击通知时,将调用以下方法。
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
}
关于ios - 为 iOS 10+ 注册通知 - 未收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49411461/