How to get the device token from new xCode 8, Swift 3 in iOS 10?
Here is the code to register notification:
<Faced the same problem, this is the only thing that helped me:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = String(format: "%@", deviceToken as CVarArg)
.trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
.replacingOccurrences(of: " ", with: "")
}
Code from Mixpanel library
let tokenChars = (deviceToken as NSData).bytes.assumingMemoryBound(to: CChar.self)
var tokenString = ""
for i in 0..<deviceToken.count {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
One line:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let apnsDeviceToken = deviceToken.map {String(format: "%02.2hhx", $0)}.joined()
}
From this tutorial.
Or a modular/encapsulated/OOP way:
extension Data {
var string: String {
return map {String(format: "%02.2hhx", $0)}.joined()
}
}
Then you can do this:
let token = deviceToken.string
It could work:
let chars = UnsafePointer<CChar>((deviceToken as NSData).bytes.assumingMemoryBound(to:CChar.self))
Thanks!
This method may solve your problem in iOS 10 and greater:
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(token)
}
The below snnipet is working with Eric Aya solution :
let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
Thanks for all help :)