Objective C中的NSData到NSString

时间:2011-06-02 13:50:35

标签: objective-c nsstring nsdata

我正在将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¨·¦ù¯ä

我甚至尝试过使用NSASCIIStringEncoding。 我究竟做错了什么 ?

2 个答案:

答案 0 :(得分:2)

尝试使用以下方法并将[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; 
}

答案 1 :(得分:1)

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

NSLog(@"Token: [%@]", [devToken description]);

要删除非数字字符,请执行以下操作:

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