【问题标题】:Device token not generate iOS device设备令牌不生成 iOS 设备
【发布时间】:2020-06-18 10:03:30
【问题描述】:

我尝试了很多时间,但没有调用didRegisterForRemoteNotificationsWithDeviceToken 方法。我花了很多时间。如果有人有解决方案,请告诉我。

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){

     let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
}

以下函数用于didFinishLaunchingWithOptions 中的AppDelegate 中的注册通知。

    func registerNotification(application:UIApplication) -> Void {

        if #available(iOS 10.0, *){
            UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
                if (granted)
                {
                    DispatchQueue.main.async {
                        UIApplication.shared.registerForRemoteNotifications()
                    }
                }
                else{
                    print("Noti Not registered !!")
                    //Do stuff if unsuccessful...
                }
            })
        }
        else { //If user is not on iOS 10 use the old methods we've been using
            let notificationSettings = UIUserNotificationSettings(
                types: [.badge, .sound, .alert], categories: nil)
            application.registerUserNotificationSettings(notificationSettings)
        }
    }

【问题讨论】:

标签: ios swift xcode push-notification devicetoken


【解决方案1】:

应用以下代码获得通知权限

  1. 在签名和功能中启用后台模式

  1. AppDelegate
    self.registerForPushNotifications(application: application)
    func registerForPushNotifications(application: UIApplication) {

            if #available(iOS 10.0, *) {
                // For iOS 10 display notification (sent via APNS)
                UNUserNotificationCenter.current().delegate = self

                let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
                UNUserNotificationCenter.current().requestAuthorization(
                    options: authOptions,
                    completionHandler: {_, _ in })
            } else {
                let settings: UIUserNotificationSettings =
                    UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
                application.registerUserNotificationSettings(settings)
            }

            application.registerForRemoteNotifications()

        }

        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let token = deviceToken.description().trimmingCharacters(in: CharacterSet(charactersIn: "<>"))

            strDeviceToken = token.replacingOccurrences(of: " ", with: "")
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 2013-10-31
    • 2016-11-24
    相关资源
    最近更新 更多