iosobjective-capple-push-notificationsnsstringnsdata

How can I convert my device token (NSData) into an NSString?


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?


Solution

  • Note - This will not work when compiling with the iOS 13 or later SDK

    use this :

    NSString * deviceTokenString = [[[[deviceToken description]
                             stringByReplacingOccurrencesOfString: @"<" withString: @""] 
                            stringByReplacingOccurrencesOfString: @">" withString: @""] 
                           stringByReplacingOccurrencesOfString: @" " withString: @""];
            
    NSLog(@"The generated device token string is : %@",deviceTokenString);