gpt4 book ai didi

ios - 如何将 iOS 设备 token 字符串转换回 NSData

转载 作者:行者123 更新时间:2023-12-01 18:41:55 34 4
gpt4 key购买 nike

我确定以前有人问过这个问题,但我一直找不到正确的答案。

在 Objective-C 中你有这个:

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

太棒了,deviceToken 不是字符串,所以通常您将其转换为字符串并将其发送到需要 NSData 的方法(精确目标示例:

[[ETPush pushManager] registerDeviceToken:deviceToken];

一切都很好 :)

问题是,在我的设置中,我从 原始 deviceToken 函数之外调用该方法,因此我实际上已经可以访问作为字符串的 token 。所以我需要做的是将该字符串 back 转换为 deviceToken NSData 对象。我可以这样做以将其转换为 NSData 对象:

NSData *deviceToken = [stringToken dataUsingEncoding:NSUTF8StringEncoding];

但问题是,当我查看描述时,我会得到类似这样的信息:

<63333833 30613765 ... 64386561 30653861 61356164 31353338 35623665 34396563>

如果您查看问题的每一个实现,我如何将 NSData 设备 token 转换为 NSString?他们的回答是这样的(或使用字节的类似内容):

NSString * deviceTokenString = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""];

正如您所想象的那样,将我发布的字符串放在上面并在该方法中使用它,它会创建如下内容:

6333383330613765....etc.

这显然不是我的设备 token :)

那么问题来了!

如何将其转换回可发送给这些方法的 NSData 对象?

最佳答案

我明白了!我能够使用这个非常有用的链接来做到这一点:

http://iphoneappcode.blogspot.com/2012/04/nsdata-to-hexstring-and-hexstring-to.html

- (NSData *)dataFromHexString:(NSString *)string
{
NSMutableData *stringData = [[[NSMutableData alloc] init] autorelease];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [string length] / 2; i++) {
byte_chars[0] = [string characterAtIndex:i*2];
byte_chars[1] = [string characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[stringData appendBytes:&whole_byte length:1];
}
return stringData;
}

然后:

NSData *deviceToken = [self dataFromHexString:myStringToken];

:)

关于ios - 如何将 iOS 设备 token 字符串转换回 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41555543/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com