1

我的AppDelegate.m. 我想要我的deviceToken价值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];
 }

但是当我显示时NSLog(@"%@",tokenStr);UIViewController我得到了(NULL). 我怎样才能得到我的价值UIViewController

4

3 回答 3

3

AppDelegate中,您可以将deviceToken值保存在NSUserDefaultslike

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

并使用从任何视图控制器中检索该值

[[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];
于 2012-12-05T07:10:24.617 回答
1

您可以使用[UIApplication sharedApplication].delegate.
这取决于您的需求。类似于你真正应该保存在 NSUserDefaults 中的令牌,它是为保存用户的凭据和令牌而设计的。但是如果你想在任何 viewController 中使用 AppDelegate 的所有公共属性和方法,你可以使用它的委托。

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSString *token = appDelegate.token;
于 2012-12-05T07:41:20.327 回答
1

在 AppDelegate.m 类中:

- (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 !! :)

于 2014-06-27T06:21:57.233 回答