4

こんにちは、アプリケーションでデバイス トークンを取得しています。通知を送信するためにサーバーに渡しています。デバイス トークンをフォームから取得する必要があるため、個別の通知を送信したいと考えていますUIViewControllerAppdelegateまたは からのデバイス トークンUIViewController

デバイストークンを取得するための私のコードAppdelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeNone)];
     return YES;
}

デバイストークン。

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
   {
      const char* data = [deviceToken bytes];
      NSMutableString * token = [NSMutableString string];

    for (int i = 0; i < [deviceToken length]; i++) {
       [token appendFormat:@"%02.2hhX", data[i]];
    }

   NSString *urlString = [NSString stringWithFormat:@"url?token=%@",token];

   NSURL *url = [[NSURL alloc] initWithString:urlString];
   NSLog(@"token %@",urlString);


   NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
   NSLog(@"request %@ ",urlRequest);
   NSData *urlData;
   NSURLResponse *response;
   urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:nil];
   NSLog(@"data %@",urlData);

  }

UIViewControllerを使用してデバイス トークンを取得しました。デバイス トークンを my に渡す方法、または my からデバイス トークンを取得する方法を教えてくださいUIViewController

4

5 に答える 5

0

デリゲート ファイルで以下のメソッドを宣言および定義します。

#pragma mark - Get / Set Device Token
+ (void)setDeviceToken:(NSString *)token {
    if(token) {
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"DeviceToken"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

+ (NSString *)getDeviceToken {
    NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"DeviceToken"];
    if(token) {
        return token;
    }
    return @"";
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceTokenメソッド呼び出しでは、[AppDelegate setDeviceToken:token];トークンを取得したら、

プロジェクトでは、任意のView Controllerで、NSString *token = [AppDelegate getDeviceToken];保存されたトークンを取得するために呼び出すことができAppDelegateます。トークンを取得します。

取得時に、保存されたトークンの可用性を確認できます

NSString *token = [AppDelegate getDeviceToken];
if(token.length) {
    // do something
}
于 2014-05-10T12:04:52.073 に答える