In my iPhone app I am getting the device token from Apple which I am assigning a public property inside the Delegate file as shown below:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
self.dToken = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
}
The dToken property is declared as shown below:
NSString *dToken;
@property (nonatomic,retain) NSString *dToken;
But when I try to retrieve the device token from another file I get the null value.
+(NSString *) getDeviceToken
{
NSString *deviceToken = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] dToken];
NSLog(@" getDeviceToken = %@",deviceToken); // This prints NULL
return deviceToken;
}
What am I doing wrong?
I suggest you to convert token to string in this way:
UPDATED: As many people mentioned it is better to use next approach to convert
NSData *
toNSString *
:From the discussion at Best way to serialize an NSData into a hexadeximal string, here is a better way to do it. Is longer, but your code will be future-proof if Apple changes the way NSData emit debugger descriptions.
Extend NSData as follows:
I know that this is an old question and that this may be new information that has come up since then, but I'd just like to point something out to all of the people who are claiming that using the description method is a really bad idea. In most cases, you'd be exactly right. The description property is generally just used for debugging, but for the NSData class, it's specifically defined as returning a hexadecimal representation of the receivers contents which is exactly what is needed here. Since Apple has put it in their documentation, I think you're pretty safe as far as them changing it.
This can be found in the NSData Class Reference here: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html