I am trying to find a way to make it possible for the user to find their device token (for debugging reasons).
...
@interface MyAppDelegate : UIResponder <UIApplicationDelegate> {
NSString *token;
}
@property (nonatomic, retain) NSString *token;
...
...
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
_token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
_token = [_token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSUInteger lenthtotes = [_token length];
NSUInteger req = 64;
if (lenthtotes == req){
NSLog(@"uploaded token: %@", _token);
upload_token = _token;
} else {
_token = @"";
}
...
NSString *token;
- (void)viewDidLoad
{
[super viewDidLoad];
MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];
token = appDelegate.token;
NSLog(token);
...
The log within the AppDelegate
works fine and returns the device token.
But the log inside the ViewController
returns nothing how come ?
It is normal that you can't retrieve the token this way because in the viewDidLoad
method of your view controller you didn't get your token yet.
Instead of retrieving it from the AppDelegate
, you should push it. I would use a notification for that :
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [_token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSUInteger lenthtotes = [_token length];
NSUInteger req = 64;
if (lenthtotes == req) {
NSLog(@"uploaded token: %@", token);
NSNotification *notif = [NSNotification notificationWithName:@"NEW_TOKEN_AVAILABLE" object:token];
[[NSNotificationCenter defaultCenter] postNotification:notif];
}
...
}
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tokenAvailableNotification:)
name:@"NEW_TOKEN_AVAILABLE"
object:nil];
}
- (void)tokenAvailableNotification:(NSNotification *)notification {
NSString *token = (NSString *)notification.object;
NSLog(@"new token available : %@", token);
}
- (void)dealloc {
[NSNotificationCenter defaultCenter] removeObserver:self];
}