1

に次のメソッドがありますAppDelegate.mdeviceTokenの値が欲しい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保存できますdeviceTokenNSUserDefaults

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

を使用して任意のView Controllerからその値を取得します

[[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];
于 2012-12-05T07:10:24.617 に答える
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];
}

ViewController クラスの viewDidLoad メソッド内:

    [super viewDidLoad];

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

これは私のデバイスで完全に機能しています。ハッピーコーディング!! :)

于 2014-06-27T06:21:57.233 に答える
1

で AppDelegate への参照を持つことができます[UIApplication sharedApplication].delegate
それはあなたのニーズに依存します。NSUserDefaults に実際に保存する必要があるトークンのようなもので、ユーザーの資格情報とトークンを保存するために設計されています。ただし、任意の viewController で AppDelegate のすべてのパブリック プロパティとメソッドを使用する場合は、そのデリゲートを使用できます。

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