Reputation: 4723
I have the following method in my AppDelegate.m
. I want the value of deviceToken
in my UIViewController
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(@"My token is: %@", deviceToken);
ViewController *viewController = [[ViewController alloc]initWithNibName:@"ViewController" bundle:nil];
viewController.tokenStr = [NSString stringWithFormat:@"%@",deviceToken];
}
but when I display NSLog(@"%@",tokenStr);
in UIViewController
I'm getting (NULL)
.
how can I get the value in my UIViewController
?
Upvotes: 1
Views: 3868
Reputation: 615
In AppDelegate.m class:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(@"My token is: %@", deviceToken);
NSString *device = [deviceToken description];
device = [device stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
device = [device stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"My device is: %@", device);
[[NSUserDefaults standardUserDefaults] setObject:device forKey:@"MyAppDeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
In ViewController class, inside viewDidLoad method:
[super viewDidLoad];
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAppDeviceToken"];
NSLog(@"device token in controller: %@ ", deviceToken);
This is working perfectly in my device. Happy Coding !! :)
Upvotes: 1
Reputation: 2921
You can have a reference to AppDelegate with [UIApplication sharedApplication].delegate
.
It depends on your needs. Something like a token you really should save in NSUserDefaults, it was designed for saving user's credentials and tokens. But if you want to use all public properties and methods of AppDelegate in any viewController, you can use it's delegate.
AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *token = appDelegate.token;
Upvotes: 1
Reputation: 6413
In AppDelegate
, you can save the deviceToken
value in NSUserDefaults
like
[[NSUserDefaults standardUserDefaults] setObject:deviceToken forKey:@"DeviceToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
and Retrieve that value from any View Controller using
[[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];
Upvotes: 3