ios - 为 iOS 10+ 注册通知 - 未收到通知

标签 ios swift xcode push-notification apple-push-notifications

在 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/

相关文章:

ios - 找不到接受类型 'UIImage' 的参数列表的类型 '(named: UIImage?)' 的初始值设定项

swift - 比较 Swift 中的 Objective-C 枚举值

xcode - 如何在Xcode 4.5中关闭垃圾收集,并在打开ARC时摆脱clang错误1?

Xcode 中的 C++ 字符串

xcode - iOS 配置 get-task-allow AND <Error> : profile not valid: 0xe8008012

ios - 如何将 Autodesk Forge Viewer 嵌入移动应用程序?

ios - 防止 Realm 在更新对象时覆盖属性

swift - 如何使用命名参数调用函数

ios - 使用文本字段聚焦错误 View

ios - 如何将视差效果应用于包含水平 UICollectionView 的 UITableView header ?