2

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?

Ron
  • 3,055
  • 1
  • 20
  • 21
  • What do you currently have in the way of the model component of your application, in model-view-controller terms? – Tommy Dec 19 '12 at 00:46

2 Answers2

9

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.

squelart
  • 11,261
  • 3
  • 39
  • 43
warrenm
  • 31,094
  • 6
  • 92
  • 116
  • 3
    Thanks for above code. Only the last line did not work for me. Instead of `stringforKey`, I used `objectforKey` and then it worked perfectly. :) – Anu Padhye Jun 27 '14 at 06:32
  • I was trying to resolve this problem for some days, till I found Your version, which is working perfect! Thank you! – RydelHouse Dec 12 '14 at 13:11
0

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

Paul R
  • 208,748
  • 37
  • 389
  • 560
Deepak
  • 1,278
  • 3
  • 15
  • 23