2

我可以通过以下方法获取 deviceToken,现在我想知道如何注册 deviceToken 以进行推送通知,因为在获取设备令牌后我不确定使用哪种方法或 API 为推送通知注册设备令牌以及这个注册过程是如何运作的?

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"APN device token: %@", deviceToken);
}
4

1 回答 1

11

好吧,首先我想确保您是否在registerForRemoteNotificationTypes应用程序启动时运行以下内容。这是您可以添加到 AppDelegate 的内容

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{       

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
                (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];

    self.window.rootViewController = self.tabBarController;

    [self.window makeKeyAndVisible];

    return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

    // Send the deviceToken to server right HERE!!! (the code for this is below)

    NSLog(@"Inform the server of this device  token: %@", deviceToken);  
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
    // Place your code for what to do when the ios device receives notification
    NSLog(@"The user info: %@", userInfo);
}


- (void)application:(UIApplication *) didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    // Place your code for what to do when the registration fails
    NSLog(@"Registration Error: %@", err);
}

当您提到为推送通知注册设备令牌时,您必须将 deviceToken 发送到发送推送通知的服务器,并让服务器将其保存在数据库中以进行推送。这是一个如何将其发送到服务器的示例。

NSString *host = @"yourhost";
NSString *URLString = @"/register.php?id=";
URLString = [URLString stringByAppendingString:id];
URLString = [URLString stringByAppendingString:@"&devicetoken="];

NSString *dt = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    dt = [dt stringByReplacingOccurrencesOfString:@" " withString:@""];

URLString = [URLString stringByAppendingString:dt];
URLString = [URLString stringByAppendingString:@"&devicename="];
URLString = [URLString stringByAppendingString:[[UIDevice alloc] name]];

NSURL *url = [[NSURL alloc] initWithScheme:@"http" host:host path:URLString];
NSLog(@"FullURL=%@", url);

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

如果您需要更多帮助,我将很乐意提供帮助。在任一网站上与我联系:Austin Web and Mobile GuruAustin Web Design

于 2011-10-03T07:42:17.583 回答