How to use the device token in method other than didRegisterForRemoteNotificationsWithDeviceToken?

冷暖自知 提交于 2020-01-11 11:08:46

问题


I got the device token through didRegisterForRemoteNotificationsWithDeviceToken method. I wanted to use the device token in another method. I tried it in this way,

In didRegisterForRemoteNotificationsWithDeviceToken method:

str = [NSString stringWithFormat:@"%@",deviceToken];
// str is the NSString which is declared in the appDelegate.h file as global variable

In didReceiveRemoteNotification method:

 NSLog(@"Device Token : %@",str);  

When i do like this the Device Token is returning as "nosniff".

How can i store this device token in a global variable and use it in the other class or in other method.


回答1:


In your app delegate class define method + (CustomAppDelegate *)sharedAppDelegate whose implementation should look like this one:

+ (CustomAppDelegate *)sharedAppDelegate
{
     return (CustomAppDelegate *) [UIApplication sharedApplication].delegate;
}

where CustomAppDelegate is name of your app delegate class.

In method your need to get value of str variable you should type following:

NSString *token = [[CustomAppDelegate sharedAppDelegate] str];

where CustomAppDelegate is name of your app delegate class and str is synthesized property (or name of the method) where device token is stored.

Before calling sharedAppDelegate don't forget to import "CustomAppDelegate.h"




回答2:


You can add the device token to the NSUserDefaults dictionary like so:

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

This can then be accessed in other methods like so:

NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];


来源:https://stackoverflow.com/questions/7804180/how-to-use-the-device-token-in-method-other-than-didregisterforremotenotificatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!