保存DeviceToken以便以后在Apple推送通知服务中使用

在我的iPhone应用程序中,我从Apple获取设备令牌,在委托文件内部分配一个公共属性,如下所示:

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { self.dToken = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding]; } 

dToken属性声明如下:

 NSString *dToken; @property (nonatomic,retain) NSString *dToken; 

但是,当我尝试从另一个文件检索设备令牌时,我得到空值。

 +(NSString *) getDeviceToken { NSString *deviceToken = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] dToken]; NSLog(@" getDeviceToken = %@",deviceToken); // This prints NULL return deviceToken; } 

我究竟做错了什么?

我build议你以这种方式将标记转换为string:

 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 

从最好的方式将NSData序列化为hexstring ,这是一个更好的方法来做到这一点。 更长时间,但是如果苹果改变了NSData发出debugging器描述的方式,你的代码将是未来的certificate。

扩展NSData如下:

 @implementation NSData (Hex) - (NSString*)hexString { unichar* hexChars = (unichar*)malloc(sizeof(unichar) * (self.length*2)); unsigned char* bytes = (unsigned char*)self.bytes; for (NSUInteger i = 0; i < self.length; i++) { unichar c = bytes[i] / 16; if (c < 10) c += '0'; else c += 'A' - 10; hexChars[i*2] = c; c = bytes[i] % 16; if (c < 10) c += '0'; else c += 'A' - 10; hexChars[i*2+1] = c; } NSString* retVal = [[NSString alloc] initWithCharactersNoCopy:hexChars length:self.length*2 freeWhenDone:YES]; return [retVal autorelease]; } @end 

我知道这是一个古老的问题,这可能是自那时以来出现的新信息,但我只想指出所有声称使用描述方法的人是一个非常糟糕的主意。 在大多数情况下,你会完全正确的。 description属性通常只用于debugging,但是对于NSData类,它的具体定义是返回接收器内容hex表示,这正是这里所需要的。 由于苹果公司已经把它放在他们的文档中,我认为就他们改变而言,你是非常安全的。

这可以在NSData类参考中find: https : //developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html