【问题标题】:Getting Remote Notification Device Token in Swift 4?在 Swift 4 中获取远程通知设备令牌?
【发布时间】:2018-05-03 07:54:24
【问题描述】:

我正在使用此代码获取通知中心设备令牌。

它在 Swift 3 中工作,但在 Swift 4 中不工作。发生了什么变化?

if #available(iOS 10.0, *) {
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in

    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {    
    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print(deviceTokenString)
}

【问题讨论】:

标签: ios swift apple-push-notifications devicetoken


【解决方案1】:

假设您已经检查了所有设置是否正确,根据您的代码,它似乎应该可以正常工作,您所要做的就是将格式更改为 %02.2hhx 而不是 %02X 以获得适当的十六进制字符串。因此,您应该得到一个有效的。

作为一个好的做法,您可以在项目中添加一个Data 扩展来获取字符串:

import Foundation

extension Data {
    var hexString: String {
        let hexString = map { String(format: "%02.2hhx", $0) }.joined()
        return hexString
    }
}

用法:

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let deviceTokenString = deviceToken.hexString
    print(deviceTokenString)
}

【讨论】:

  • 我的控件没有调用 didRegisterForRemoteNotificationsWithDeviceToken 委托。
  • 好吧,那将是 另一个 问题,如果该方法甚至无法访问,那么您遗漏了一些东西...请重新检查通知的设置。
  • 在我最后一个工作日运行良好。不是今天不知道为什么无法跟踪问题
  • %02.2hhx 会做什么?你能解释一下吗?
【解决方案2】:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
    {
        let tokenChars = (deviceToken as NSData).bytes.bindMemory(to: CChar.self, capacity: deviceToken.count)
        var tokenString = ""

        for i in 0..<deviceToken.count {
            tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
        }
                    print("tokenString: \(tokenString)")
}

【讨论】:

    【解决方案3】:

    获取设备令牌

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Convert token to string
        let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    }
    

    希望对你有帮助

    【讨论】:

      【解决方案4】:

      获取 deviceToken 的工作代码 - iOS 11 或更高版本,

      Swift 4 |斯威夫特 5

      请求用户权限

      func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
          
          let center = UNUserNotificationCenter.current()
          center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
      
              // If granted comes true you can enabled features based on authorization.
              guard granted else { return }
      
              application.registerForRemoteNotifications()
          }        
          return true        
      }
      

      获取设备令牌

      func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
          
          let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
          print(token) 
      }
      

      出现错误时

      func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
      
          print("i am not available in simulator :( \(error)")
      }
      

      【讨论】:

      • 为什么那些演示代码中的application方法(Request user permissionGetting device tokenIn case of error)有不同的签名?是否存在可以处理您提到的所有这些情况的签名版本上面?
      • @zionpi 是的,您需要从功能启用推送通知,然后 registerForRemoteNotifications 以获取令牌
      • 这意味着这三个不同的application 方法可以同时在ONE单个应用程序上调用? @Nikunj Kumbhani
      • @zionpi 是的,这都是为远程通知注册设备的委托方法
      【解决方案5】:

      你可以像这样获取设备令牌:

      func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
          let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
          print("Device Token : ",token)
      }
      

      【讨论】:

        【解决方案6】:

        使用以下代码获取设备令牌:

         func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        
            var token = ""
            for i in 0..<deviceToken.count {
                token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
            }
            print("Device Token = \(token)")
        
        
        
        }
        

        【讨论】:

          【解决方案7】:

          斯威夫特 5

          你可以用like,

          func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
              let hexString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
              print(hexString)
          }
          

          【讨论】:

            【解决方案8】:

            您可以使用这两个函数来获取设备令牌和 FCM 令牌:


            对于设备令牌,请使用:

            func application(_ application:UIApplication,didRegisterForRemoteNotificationsWithDeviceToken 
            devicetoken: Data)
             {
                    let deviceTokenString = deviceToken.hexString
                    print(deviceTokenString)
             }
            

            对于 FCM 令牌,请使用:

            func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
                print("Firebase registration token: \(fcmToken)")
                userDefault.set(fcmToken, forKey: "fcmToken")
            
            }
            

            对于 UUID,请使用:

             let deviceIds = UIDevice.current.identifierForVendor!.uuidString
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-02-06
              • 1970-01-01
              • 1970-01-01
              • 2016-05-08
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多