0

I am trying to get the device token in my AppDelegate, and then use it in a function in my ViewController later.

I successfully retrieve the device token like so in the AppDelegate:

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSString *tokenAsString = [[[deviceToken description]
                                 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                                stringByReplacingOccurrencesOfString:@" " withString:@""];

    [[NSUserDefaults standardUserDefaults] setObject: token forKey:@"deviceToken"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

Then I am trying to use it in a function in my ViewController, but it is printing as null:

-(void)addDeviceToken{
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
    NSLog(@"%@", deviceToken);
}

Does anyone know how to get the variable to show up here?

jape
  • 2,861
  • 2
  • 26
  • 58
  • Why is your method called `-addDeviceToken` if you are _retrieving_ the device token? (_not_ storing it). Naming consistency might sound superfluous, but it all adds up and comes back to bite you when you revisit your code -say- three months from now. Clarity pays off. – Nicolas Miari Jan 07 '16 at 02:09
  • 1
    If you nslog the token string value in the app delegate before saving does it look like a valid nsstring? – Dallas Johnson Jan 07 '16 at 02:11
  • 1
    @NicolasMiari I am adding it to my server's database. – jape Jan 07 '16 at 02:59
  • @DallasJohnson Nothing prints when I do that. It's as if I didn't put `NSLog`, even though I did. I guess that's my first problem to figure out why that's happening – jape Jan 07 '16 at 03:00
  • What is the "token" string which you use in didRegisterForRemoteNotificationsWithDeviceToken method? Use "tokenAsString" for set "deviceToken" object. – hmlasnk Jan 07 '16 at 04:14
  • If NSLog isn't printing anything, it means that method isn't being called.. – Skywalker Jan 07 '16 at 05:05

1 Answers1

1

Replace token with tokenAsString.

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *tokenAsString = [[[deviceToken description]
                             stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                            stringByReplacingOccurrencesOfString:@" " withString:@""];

[[NSUserDefaults standardUserDefaults] setObject: tokenAsString forKey:@"deviceToken"];
[[NSUserDefaults standardUserDefaults]synchronize];}
Sanket_B
  • 735
  • 9
  • 26