Reputation: 1508
Using swift 3.0, I am trying to convert a deviceToken (data) to string, but it is not returning the correct string.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let tokenString = deviceToken.reduce("") { string, byte in
string + String(format: "%02X", byte)
}
print("token: ", tokenString)
}
Does anyone know what I am doing wrong?
Upvotes: 0
Views: 255
Reputation: 453
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)
Hope this will help you to get exact devicetoken for sending to your server.
Upvotes: 0
Reputation:
You can convert it using this method as device tokens is an array of UInt8 in the form of bytes you have describe every byte.
let token = String(describing: deviceToken as CVarArg).replaceCharacters("<> ", toSeparator: "")
I have created extension to String as I use replaceCharacters() frequently
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
}
}
Upvotes: 0
Reputation: 285180
In Swift 3 it's a bit easier because Data
behaves like an array:
let tokenString = deviceToken.map{ String(format: "%02X", $0) }.joined()
Upvotes: 3