0

I know this is very basic but I need to pull my device token and Store it in a String and put(display) it on a label on my ViewDidLoad method. What might be the posible solution? Im new on iOS development. Should I use Global variable? or any Posible Solution?

This is my code.

AppDelegate.m

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

NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];

NSLog(@"%@", str);

//get the string and display it on the ViewDidLoad method.

}

Please help me. How to use global variable to access that string?

on my ViewController.m class

- (void)viewDidLoad
{
   [super viewDidLoad];

   NSString *getToken = @"Token from AppDelegate";

}

Something like that.

Jarich
  • 337
  • 2
  • 9
  • 25

2 Answers2

2

You can store the token into user defaults:

[[NSUserDefaults standardUserDefaults] setValue:str forKey:@"DEVICE_TOKEN"];

And then in your viewDidLoad:

NSString *getToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"DEVICE_TOKEN"];

But there are other approaches: global variable, persistence layer, NSNotification, and so on.

EDIT:

Here you have info about how to register the standard user defaults.

EDIT2:

In order to obtain the token string, I do the following

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

Then, in deviceTokenString you end having the full value without whitespaces or any other character. Just ready to trigger push notifications.

Community
  • 1
  • 1
amb
  • 4,798
  • 6
  • 41
  • 68
  • 1
    You should really be doing the conversion from data to a hex string manually, instead of relying on the implementation of -[NSData description]. – Tyler Aug 08 '13 at 09:16
0

I usually create a category on UIApplication (or a UIApplication subclass) for storing the current push token.

@interface MyApplication : UIApplication

@property (nonatomic, copy) NSData *pushToken;

@end

As @amb mentioned, there are a lot of different ways to go about it.

Tyler
  • 371
  • 1
  • 7