Objective c Objective中的NSData到NSString

Objective c Objective中的NSData到NSString,objective-c,nsstring,nsdata,Objective C,Nsstring,Nsdata,我正在将NSData格式的APN设备令牌转换为NSString,但我是一些特殊字符 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { NSLog(@"Device Token 111 : %@", deviceToken); NSString *deviceStr = [[NSStri

我正在将NSData格式的APN设备令牌转换为NSString,但我是一些特殊字符

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

    NSLog(@"Device Token 111 : %@", deviceToken);

    NSString *deviceStr = [[NSString alloc] initWithData:deviceToken encoding:NSUTF8StringEncoding];
    NSLog(@"Device Token : %@", deviceStr);
    [deviceStr release];
}

Device Token 111 : <d8b62879 48de8f9f 90507519 da1d39cf 1b700f7f 022dcaf4 7532a8b7 a6f9afe4>
Device Token : ض(yHÞPuÚ9Ïep-Êôu2¨·¦ù¯ä
-(void)应用程序:(UIApplication*)应用程序DIDregisterforRemotionTificationswithDeviceToken:(NSData*)deviceToken{
NSLog(@“设备令牌111:%@”,deviceToken);
NSString*deviceStr=[[NSString alloc]initWithData:deviceToken编码:NSUTF8StringEncoding];
NSLog(@“设备令牌:%@”,deviceStr);
[设备TR发布];
}
设备令牌111:
设备令牌:ØØ(yHÞPuÚ9Ïep-Êôu2ùùù)
我甚至尝试过NSASCIIStringEncoding。
我做错了什么?

尝试使用以下方法,将
[deviceToken bytes]
作为第一个参数

const static char hexchar[] = "0123456789ABCDEF";
- (NSString*) bytes2hex:(const char* ) buffer length:(int)buf_len {
    size_t i;
    char *p;
    int len = (buf_len * 2) + 1;
    p = malloc(len);
    for (i = 0; i < buf_len; i++) {
        p[i * 2] = hexchar[(unsigned char)buffer[i] >> 4 & 0xf];
        p[i * 2 + 1] = hexchar[((unsigned char)buffer[i] ) & 0xf];
    }
    p[i * 2] = '\0';
    NSString * result = [NSString stringWithCString:p encoding:NSUTF8StringEncoding];
    free(p); 
    return result; 
}
const static char hexchar[]=“0123456789ABCDEF”;
-(NSString*)字节数2hex:(const char*)缓冲区长度:(int)buf_len{
尺寸i;
char*p;
int len=(buf_len*2)+1;
p=malloc(len);
对于(i=0;i>4&0xf];
p[i*2+1]=hexchar[(无符号字符)缓冲区[i])&0xf];
}
p[i*2]='\0';
NSString*result=[NSString stringWithCString:p编码:NSUTF8STRINGENCONDING];
自由基(p);
返回结果;
}

您可以使用description方法获取令牌的字符串表示形式

NSLog(@"Token: [%@]", [devToken description]);
要删除非数字字符,可以执行以下操作:

NSCharacterSet *set = [[NSCharacterSet alphanumericCharacterSet] invertedSet];    
NSString *tkn = [[[devToken description] componentsSeparatedByCharactersInSet:set] componentsJoinedByString: @""];

尝试迭代NSData*的字节,将它们转换为char并记录它们,查看它们是否显示为
,在您的示例中,标记是
(yHÞPuÚ9Ïep-Êu2¨alphaùä
unicode格式。令牌不是存储在
NSData
对象中的字符串。它也不同于设备的序列号。请阅读文档。为什么要将令牌转换为字符串?令牌是加密数据,因此它只是无意义的字节,而不是有意义的文本:“APNs使用唯一设备证书中包含的信息生成设备令牌。设备令牌包含设备标识符。然后,它使用令牌密钥加密设备令牌并将其返回到设备”()。为什么要重写
%hhx
(字节格式为十六进制)<代码> Prtff<代码>格式说明符,而不只是使用<代码> SNPROTFF < /代码>?更简单的是使用相同的格式说明符使用<代码> -[nSMutabeString AppDeField::/Case>。没有<代码> MALLC/<代码>,没有<代码>免费< /代码>,不依赖用于表示C字符串文字的字符集——只是基础方法。