I am implementing push notifications. I'd like to save my APNS Token as a String.
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
NSString *tokenString = [NSString stringWithUTF8String:[newDeviceToken bytes]]; //[[NSString alloc]initWithData:newDeviceToken encoding:NSUTF8StringEncoding];
NSLog(@"%@", tokenString);
NSLog(@"%@", newDeviceToken);
}
The first line of code prints null. the second prints the token. How can I get my newDeviceToken as an NSString?
For Swift :
Swift 3:
If any one is looking for a way to get device token in Swift 3. Use the below modified snippet.
I've tried to test two different methods with format
"%02.2hhx"
and"%02x"
and the result is that the fastest is
"%02x"
at average 2.0 vs 2.6 for the reduced version:If anyone is looking for a way to do this in Swift:
Edit: For Swift 3
Swift 3 introduces the
Data
type, with value semantics. To convert thedeviceToken
to a String, you can do as follows:You could use this