我试图在我的AppDelegate中获取设备令牌,然后在以后的ViewController中的函数中使用它。

我在AppDelegate中成功检索了设备令牌:

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    NSString *tokenAsString = [[[deviceToken description]
                                 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                                stringByReplacingOccurrencesOfString:@" " withString:@""];

    [[NSUserDefaults standardUserDefaults] setObject: token forKey:@"deviceToken"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}


然后,我试图在ViewController的函数中使用它,但它打印为null

-(void)addDeviceToken{
    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"deviceToken"];
    NSLog(@"%@", deviceToken);
}


有谁知道如何让变量显示在这里?

最佳答案

用tokenAsString替换令牌。

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
NSString *tokenAsString = [[[deviceToken description]
                             stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
                            stringByReplacingOccurrencesOfString:@" " withString:@""];

[[NSUserDefaults standardUserDefaults] setObject: tokenAsString forKey:@"deviceToken"];
[[NSUserDefaults standardUserDefaults]synchronize];}

关于ios - 将设备 token 存储在AppDelegate中,然后在ViewController中使用它,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34646026/

10-12 00:30