【问题标题】:Unable to convert correct device token in swift 3.0无法在 swift 3.0 中转换正确的设备令牌
【发布时间】:2017-01-07 07:11:02
【问题描述】:

使用 swift 3.0,我正在尝试将 deviceToken(数据)转换为字符串,但它没有返回正确的字符串。

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

    let tokenString = deviceToken.reduce("") { string, byte in
        string + String(format: "%02X", byte)
    }
    print("token: ", tokenString)

}

有谁知道我做错了什么?

【问题讨论】:

  • 你得到了什么,你期望什么?

标签: swift xcode push-notification swift3 xcode8.1


【解决方案1】:

在 Swift 3 中它更容易一些,因为 Data 的行为类似于数组:

let tokenString = deviceToken.map{ String(format: "%02X", $0) }.joined()

【讨论】:

  • 除非我弄错了,否则这将给出与使用 Swift 3 中的数据序列的 OP 代码完全相同的结果。
【解决方案2】:

您可以使用此方法对其进行转换,因为设备令牌是一个 UInt8 数组,其形式为您描述每个字节的字节。

let token = String(describing: deviceToken as CVarArg).replaceCharacters("<> ", toSeparator: "")

由于我经常使用 replaceCharacters(),我创建了对 String 的扩展

extension String { func replaceCharacters(_ characters: String, toSeparator: String) -> String { let characterSet = CharacterSet(charactersIn: characters) let components = self.components(separatedBy: characterSet) let result = components.joined(separator: toSeparator) return result } }

【讨论】:

    【解决方案3】:
     var token = NSData.init(data: deviceToken).description
        token = token.replacingOccurrences(of: "<", with: "")
        token = token.replacingOccurrences(of: " ", with: "")
        token = token.replacingOccurrences(of: ">", with: "")
        token = String.init(describing: token)
    
        print(token)
    

    希望这将帮助您获得准确的设备令牌以发送到您的服务器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多