stepik21
stepik21

Reputation: 2640

Get data from AppDelegate to ViewController in iOS

i have ios project i xcode and I need to get device token from Appdelegate to view controller, here is code of App delegate:

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{    
    [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"token"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

And then, in view controller:

[super viewDidLoad];    
[[NSUserDefaults standardUserDefaults] objectForKey:@"token"];

When I try it for the first time, it was working, but next time app crahed... When I remove that code from view controller, it works, so it must be wrong there... Can you help me?

Upvotes: 1

Views: 1304

Answers (1)

Thilina Chamath Hewagama
Thilina Chamath Hewagama

Reputation: 9040

First of all, delete your app from your phone/simulator.
Because the NSUserDefaults may hold wrong data for your key.

enter image description here

then replace your code with these,

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    if(deviceToken){
        [[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}


In viewDidLoad,

- (void)viewDidLoad
{
    [super viewDidLoad];
    id token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if(token){
        NSLog(@"I have got the token");
    }else NSLog(@"no token");
}

Upvotes: 2

Related Questions