2012-12-05 112 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); 

這是在我的設備可以正常使用。快樂編碼! :)

相關問題