Swift 3 - device tokens are now being parsed as &#

2019-01-21 12:19发布

I just updated from Xcode 7 to the 8 GM and amidst the Swift 3 compatibility issues I noticed that my device tokens have stopped working. They now only read '32BYTES'.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print(deviceToken) // Prints '32BYTES'
    print(String(data: deviceToken , encoding: .utf8)) // Prints nil
}

Before the update I was able to simply send the NSData to my server, but now I'm having a hard time actually parsing the token.

What am I missing here?

Edit: I just testing converting back to NSData and I'm seeing the expected results. So now I'm just confused about the new Data type.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print(deviceToken) // Prints '32BYTES'
    print(String(data: deviceToken , encoding: .utf8)) // Prints nil

    let d = NSData(data: deviceToken)
    print(d) // Prints my device token
}

标签: ios swift swift3
11条回答
神经病院院长
2楼-- · 2019-01-21 12:36

I just did this,

let token = String(format:"%@",deviceToken as CVarArg).components(separatedBy: CharacterSet.alphanumerics.inverted).joined(separator: "")

it gave the result same as,

let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
查看更多
Bombasti
3楼-- · 2019-01-21 12:43

try this

if #available(iOS 10.0, *) {
   let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
}
查看更多
我只想做你的唯一
4楼-- · 2019-01-21 12:44

The device token has never been a string and certainly not a UTF-8 encoded string. It's data. It's 32 bytes of opaque data.

The only valid way to convert the opaque data into a string is to encode it - commonly through a base64 encoding.

In Swift 3/iOS 10, simply use the Data base64EncodedString(options:) method.

查看更多
冷血范
5楼-- · 2019-01-21 12:45

This one wasn't stated as an official answer (saw it in a comment), but is what I ultimately did to get my token back in order.

let tokenData = deviceToken as NSData
let token = tokenData.description

// remove any characters once you have token string if needed
token = token.replacingOccurrences(of: " ", with: "")
token = token.replacingOccurrences(of: "<", with: ""
token = token.replacingOccurrences(of: ">", with: "")
查看更多
该账号已被封号
6楼-- · 2019-01-21 12:48

Swift 3

The best and easiest way.

deviceToken.base64EncodedString()
查看更多
登录 后发表回答