Greg
Greg

Reputation: 21

How to request device token on iphone

I am able to use the didRegisterForRemoteNotificationWithDeviceToken callback method to get the device token of my iphone when subscribing to push notifications. My question is how can I get this token again a later time? When a user subscribes to something in my application, I want to send the device token and the id of the item they are subscribing to...but I can't figure out where to get the device token from. I tried using the uniqueIdentifer from the UIDevice class but this value is different than what the original token was. I supposed I could call registerForRemoteNotificationTypes each time my app starts to produce the token. But if I do that, I'm not sure how I can access this value from a different class (my didRegisterForRemoteNotificationWithDeviceToken callback is located in the main application delegate). Thanks for any help for an objective C newbie!

Upvotes: 2

Views: 5032

Answers (1)

Tom Irving
Tom Irving

Reputation: 10069

I would set a property in your appDelegate that can be accessed from anywhere, and set it to the device token.

// .h
@interface SomeAppDelegate : NSObject <UIApplicationDelegate> {
    NSString * dToken;
}

@property (nonatomic, retain) NSString * dToken;

// .m
@implementation SomeAppDelegate;
@synthesize dToken;

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

    NSString * token = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
    [self setDToken:token];
    [token release];
}
- (void)dealloc {
    [dToken release]
    [super dealloc];
}

You can then access that token anywhere by using:

NSString * token = [(SomeAppDelegate*)[[UIApplication sharedApplication] delegate] dToken];

Upvotes: 5

Related Questions