antonioricardof
antonioricardof

Reputation: 21

How to get the devicetoken in another class that is not the AppDelegate?

Good afternoon. I'm Brazilian so excuse me for any English errors!

I'm sending push notifications to my own device. I can get my deviceToken in my AppDelegate.m:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {  
    NSLog(@"Device Token Global : %@", deviceToken);   
}

But I have a class called LoginViewController.m where I perform a login and POST the deviceToken to a webservice (which inserts it into a mySQL table). How can I get this deviceToken as a string in my LoginViewController.m class?

Upvotes: 2

Views: 3644

Answers (2)

warrenm
warrenm

Reputation: 31782

Convert the token to a string:

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

Store the token to NSUserDefaults using an application-specific key of your choosing:

[[NSUserDefaults standardUserDefaults] setObject:tokenString forKey:@"MyAppSpecificGloballyUniqueString"];

Then, retrieve it elsewhere in your app:

NSString *tokenString = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAppSpecificGloballyUniqueString"];

You don't have to use NSUserDefaults. You can use any sort of global state, singleton object, registry, or dependency injection to pass the value around. How you do that is up to you; this is merely an example.

Upvotes: 9

Deepak
Deepak

Reputation: 1278

Use a singleton class and create a device string (deviceString).

singletonObject.deviceString = [deviceToken description];
singletonObject.deviceString = [tokenString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]; 
singletonObject.deviceString = [tokenString stringByReplacingOccurrencesOfString:@" " withString:@""];

Now you can use the singletonObject.deviceString in any other class

Upvotes: 0

Related Questions