iOS APNS:以string格式将设备令牌发送给提供者
我需要通过调用我的请求中需要JSON数据的服务将我的iOS应用程序的APNS设备令牌发送给我的提供程序。 我正在阅读苹果的本地和推送通知编程指南 ,它只是说, application:didRegisterForRemoteNotificationsWithDeviceToken:
委托方法传递设备令牌作为NSData
,你应该把它传递给您的提供商编码的二进制数据。 但我需要它被转换为string,以便能够发送一个JSON请求到我的提供者。
我也一直在阅读与此相关的几个post,因为它看起来是一种常见的情况,但我已经find了一些不同的方式来将这种设备令牌转换为string来发送它,我不知道它们中的哪一个应该是最合适的。 哪一个最可靠的方法来处理呢? 我想我的提供者将需要将这个string转换回来调用APNS,并且我还需要将此令牌存储在应用程序中,以便安全地将其与新值进行比较,如果生成新的令牌并调用application:didRegisterForRemoteNotificationsWithDeviceToken:
只有在发生变化时才发送令牌。
谢谢
你是对的,你必须将设备标记从NSData
转换为NSString
,以便能够发送一个JSON对象。 但是,您select的转换方法完全取决于您或供应商的要求。 最常见的方法是hexstring(例如,请参阅将NSData序列化为hexstring的最佳方法 )或Base64string(使用base64EncodedStringWithOptions
)。 两者都100%“可靠”。
你也应该总是把设备令牌发送给提供者,而不仅仅是当它发生了改变。 提供者必须保存所有设备令牌的数据库,并在最近发送最后一次的时间戳,以比较时间戳与“反馈服务”可能的响应。
在didFinishLaunchingWithOptions方法中
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) { [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]]; [[UIApplication sharedApplication] registerForRemoteNotifications]; } else { [[UIApplication sharedApplication] registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)]; }
在完成上面的代码之后,添加下面的方法
#pragma mark Push Notifications - (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSString *token_string = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"withString:@""] stringByReplacingOccurrencesOfString:@">" withString:@""] stringByReplacingOccurrencesOfString: @" " withString: @""]; NSString* strURL = [NSString stringWithFormat:@"http://www.sample.com?device_token=%@&type=IOS",token_string]; strURL=[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",strURL); NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]]; NSLog(@"content---%@", fileData); }
在上面列出的步骤之后,您可以使用此委托函数检索并处理推送通知。下面添加的方法将触发应用程序在后台运行。下面的方法可以从ios7.0
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))handler
const unsigned *tokenBytes = [deviceToken bytes]; NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x", ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]), ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]), ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
将数据转换为字节意味着我们可以对其进行计数。 删除空格和<>真的不是一个好主意
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)_deviceToken { NSString *str = [NSString stringWithFormat:@"%@",_deviceToken]; //replace '<' and '>' along with spaces before you send it to the server. }
这几乎在所有的networking平台上都可靠地工作。