我知道这是非常基本的,但我需要拉取我的设备令牌并将其存储在String中并将其显示在我的ViewDidLoad方法的标签上。什么是可行的解决方案?我是iOS开发的新手。我应该使用全局变量吗?或任何可行的解决方案?
这是我的代码。
AppDelegate.m
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"%@", str);
//get the string and display it on the ViewDidLoad method.
}
请帮帮我。如何使用全局变量来访问该字符串?
在我的ViewController.m类
上- (void)viewDidLoad
{
[super viewDidLoad];
NSString *getToken = @"Token from AppDelegate";
}
类似的东西。
答案 0 :(得分:2)
您可以将令牌存储到用户默认值中:
[[NSUserDefaults standardUserDefaults] setValue:str forKey:@"DEVICE_TOKEN"];
然后在你的viewDidLoad中:
NSString *getToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"DEVICE_TOKEN"];
但还有其他方法:全局变量,持久层,NSNotification
等。
编辑:
Here you have有关如何注册标准用户默认值的信息。
EDIT2:
为了获得令牌字符串,我执行以下操作
NSString *deviceTokenString = [deviceToken description];
deviceTokenString = [deviceTokenString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
deviceTokenString = [deviceTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];
然后,在deviceTokenString
中,您将获得没有空格或任何其他字符的完整值。准备好触发推送通知。
答案 1 :(得分:0)
我通常在UIApplication(或UIApplication子类)上创建一个类别来存储当前的推送令牌。
@interface MyApplication : UIApplication
@property (nonatomic, copy) NSData *pushToken;
@end
正如@amb所提到的,有很多不同的方法可以解决它。