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

时间:2011-09-29 17:22:59

标签: ios push-notification devicetoken

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

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

声明dToken属性如下所示:

NSString *dToken;

@property (nonatomic,retain) NSString *dToken;

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

+(NSString *) getDeviceToken
{
  NSString *deviceToken = [(MyAppDelegate *)[[UIApplication sharedApplication] delegate] dToken];

    NSLog(@" getDeviceToken = %@",deviceToken);  // This prints NULL

    return deviceToken; 

}

我做错了什么?

3 个答案:

答案 0 :(得分:35)

我建议您以这种方式将令牌转换为字符串:

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

答案 1 :(得分:4)

Best way to serialize an NSData into a hexadeximal string的讨论中,这是一个更好的方法。更长,但如果Apple更改NSData发出调试器描述的方式,您的代码将面向未来。

按如下方式扩展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

答案 2 :(得分:2)

我知道这是一个老问题,这可能是自那时以来出现的新信息,但我想向所有声称使用描述方法的人指出一些事情。是一个非常糟糕的主意。在大多数情况下,你是完全正确的。 description属性通常仅用于调试,但对于NSData类,它特别定义为返回接收器内容的十六进制表示,这正是这里所需要的。由于Apple已经将它放在他们的文档中,我认为只要他们改变它就会非常安全。

这可以在NSData Class Reference中找到:https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html