保存DeviceToken以便以后在Apple推送通知服务中使用 [英] Saving the DeviceToken for Later Use in Apple Push Notification Services
本文介绍了保存DeviceToken以便以后在Apple推送通知服务中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的iPhone应用程序中,我从Apple获取设备令牌,我在Delegate文件中分配了一个公共属性,如下所示:
In my iPhone app I am getting the device token from Apple which I am assigning a public property inside the Delegate file as shown below:
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
self.dToken = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
}
dToken属性声明如下:
The dToken property is declared as shown below:
NSString *dToken;
@property (nonatomic,retain) NSString *dToken;
但是当我尝试从另一个文件中检索设备令牌时,我得到空值。
But when I try to retrieve the device token from another file I get the null value.
+(NSString *) getDeviceToken
{
NSString *deviceToken = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] dToken];
NSLog(@" getDeviceToken = %@",deviceToken); // This prints NULL
return deviceToken;
}
我做错了什么?
推荐答案
我建议您以这种方式将令牌转换为字符串:
I suggest you to convert token to string in this way:
self.dToken = [[[deviceToken description]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]]
stringByReplacingOccurrencesOfString:@" "
withString:@""];
更新:
正如很多人提到的,最好使用下一种方法来转换 NSData *
到 NSString *
:
@implementation NSData (Conversion)
- (NSString *)hexadecimalString
{
const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
if (!dataBuffer) {
return [NSString string];
}
NSUInteger dataLength = [self length];
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02lx", (unsigned long)dataBuffer[i]];
}
return hexString;
}
@end
这篇关于保存DeviceToken以便以后在Apple推送通知服务中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文