Does iOS 13 has new way of getting device notification token?
You may use this method to fetch the device token on iOS 13 onwards:
Objective-C:
+ (NSString *)stringFromDeviceToken:(NSData *)deviceToken {
NSUInteger length = deviceToken.length;
if (length == 0) {
return nil;
}
const unsigned char *buffer = deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)];
for (int i = 0; i < length; ++i) {
[hexString appendFormat:@"%02x", buffer[i]];
}
return [hexString copy];
}
Swift 5.0 (Untested)
class func string(fromDeviceToken deviceToken: Data?) -> String? {
let length = deviceToken?.count ?? 0
if length == 0 {
return nil
}
let buffer = UInt8(deviceToken?.bytes ?? 0)
var hexString = String(repeating: "\0", count: length * 2)
for i in 0..<length {
hexString += String(format: "%02x", buffer[i])
}
return hexString
}
Taken from OneSignal blog
The same code for Swift 5 but bit shorter variant. Verified at iOS 13.
func getStringFrom(token:NSData) -> String {
return token.reduce("") { $0 + String(format: "%02.2hhx", $1) }
}
The way you do it is fine and it should continue to work on iOS 13. But some developers do it like this. To convert Data
into base-16 strings, they call description
, which returns something like
<124686a5 556a72ca d808f572 00c323b9 3eff9285 92445590 3225757d b83997ba>
And then they trim <
and >
and remove spaces.
On iOS 13 the description
called on token data returns something like
{ length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f ... 28f10282 14af515f }
Which obviously makes this way broken.
Another example of wrong implementation (already edited to include correct implementation as well).
Some more examples might be found in this thread.