一直以来使用的解析方式(iOS13之前)都是如下:
Objective-C:
代码语言:javascript复制NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
Swift:
代码语言:javascript复制let dataStr = NSData(data: deviceToken)
let token = dataStr.description
.replacingOccurrences(of: "<", with: "")
.replacingOccurrences(of: ">", with: "")
.replacingOccurrences(of: " ", with: "")
//当然下面这种方式性能更好:
let charactersToRemove: Set<Character> = ["<", ">", " "]
let tokenNew = dataStr.description.removeAll(where: charactersToRemove.contains)
或者类似的解析方式,都是替换< >
和空字符串
这种方法.
在stackoverflow中有人说过这样的解析方式并不好,但是一直没有问题,所以大家也就习惯了这样的解析方式了,但是iOS13中这样的解析方式就有问题了 大家可以更新解析方式为下面这样的方式(兼容各个版本):
- Objective-C: (这个是友盟提供的方法)
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
if (![deviceToken isKindOfClass:[NSData class]]) return;
const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [NSString stringWithFormat:@"xxxxxxxx",
ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
NSLog(@"deviceToken:%@",hexToken);
}
- Objective-C: (另一种方法)
if (![deviceToken isKindOfClass:[NSData class]]) return;
NSMutableString *valueString = [NSMutableString string];
const unsigned *tokenBytes = [deviceToken bytes];
NSInteger count = deviceToken.length;
for (int i = 0; i < count; i ) {
[valueString appendFormat:@"x", tokenBytes[i]&0x000000FF];
}
//这个也可改成for in 循环获取
- Swift:和上面方法基本一致,使用高级函数一行搞定
let token = deviceToken.map{String(format: ".2hhx", $0)}.joined()
或
代码语言:javascript复制let token = deviceToken.map{String(format: "x", $0)}.joined()
但是,有大神做过测试,下面这种方式最快
代码语言:javascript复制let token = deviceToken.reduce("", {$0 String(format: "x", $1)}) //比上面解析速度快
不过好像。。。差距基本也是看不出来的,因为我们只解析一次