2012-12-05 114 views
1

我的AppDelegate.m中有以下方法。我想的deviceToken值在我UIViewController将appdelegate数据传递给视图控制器

- (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]; 
} 

,但是当我在UIViewController显示NSLog(@"%@",tokenStr);我越来越(NULL)。 我如何获得我的UIViewController中的值?

+0

你如何显示'ViewController'?在推送该对象之前添加。 – iDev

+0

对不起,我不明白你的意思? –

+0

您可以发表您在屏幕上显示ViewController的代码。上面的代码只是创建一个对象,并没有别的。应该在屏幕上显示它。你需要在那里添加。 – iDev

回答

3

AppDelegate,您可以节省NSUserDefaultsdeviceToken值一样

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

,并使用

[[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"]; 
+0

我仍然收到NULL。 –

+0

您在哪里运行它,无论是设备还是iOS模拟器。如果你在模拟器上运行它,它总是会返回NULL。在设备中尝试。 – arthankamal

+0

我在设备上运行它。当我第一次运行它时,显示为空值,那为什么? –

1

可以从任何浏览器该值可以有一个参考与[UIApplication sharedApplication].delegate到AppDelegate中。
这取决于你的需求。就像你真的应该保存在NSUserDefaults中的令牌一样,它是为了保存用户的证书和令牌而设计的。但是如果你想在任何viewController中使用AppDelegate的所有公共属性和方法,你可以使用它的委托。

AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate; 
NSString *token = appDelegate.token; 
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]; 
} 

在视图控制器类,viewDidLoad方法中:

[super viewDidLoad]; 

    NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyAppDeviceToken"]; 
    NSLog(@"device token in controller: %@ ", deviceToken); 

这是在我的设备可以正常使用。快乐编码! :)

相关问题