2

Is it possible to get the Device Token returned from the application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken method? Since I'm not very good at PHP, I'd like for my user to manually enter the token into a program on their computer that is going to be used to send out the notification. But, I can't get the token from this method. It logs fine using NSLog, but when I use NSString initWithData:, I always get some cryptic thing. I suppose the encoding is wrong?

Thanks for your help in advance!

3 Answers 3

7

The token is an NSData object, which points to a raw binary blob of data, not a string. The two most common ways to convert it to a string would be:

  1. base64 encode it Download http://projectswithlove.com/projects/NSData_Base64.zip
NSString *str = [deviceToken base64EncodedStringWithoutNewlines];
  1. Use NSData's -description to get a string hex dump and clean it up
NSString *str = [[deviceToken description] stringByReplacingOccurrencesOfString:@"<" withString:@""];
str = [str stringByReplacingOccurrencesOfString:@">" withString:@""];
str = [str stringByReplacingOccurrencesOfString: @" " withString: @""];

I prefer #1 because the latter is dependent on the internal way that NSData's -description call works, but either should work.

1
  • I use the base64 method, but use 'url safe' base64 which is an encoding that makes the resulting string acceptable as - is in URLs, etc. The original base64 uses the '+' and '/' characters of standard Base64 are respectively replaced by '-' and '_'. Nov 27, 2012 at 14:23
3

You can get the hexadecimal string without worrying about the behaviour of NSData's description method, with:

+ (NSString *)hexadecimalStringFromData:(NSData *)data {
    NSMutableString *hexToken;
    const unsigned char *iterator = (const unsigned char *) [data bytes];
    if (iterator) {
        hexToken = [[NSMutableString alloc] init];
        for (NSInteger i = 0; i < data.length; i++) {
            [hexToken appendString:[NSString stringWithFormat:@"%02lx", (unsigned long) iterator[i]]];
        }
        return hexToken;
    }
    return nil;
}
0

Token is NSData.You can convert to string.And remove < and > and spaces

NSString *devToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
devToken = [devToken stringByReplacingOccurrencesOfString:@" " withString:@""];


NSLog(@"token: %@",devToken);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.