iOS13 DeviceToken 解析

一直以来使用的解析方式(iOS13之前)都是如下:

Objective-C:

NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];

Swift:

let dataStr = NSData(data: deviceToken)
let token = dataStr.description
  .replacingOccurrences(of: "<", with: "")
  .replacingOccurrences(of: ">", with: "")
  .replacingOccurrences(of: " ", with: "")

//当然下面这种方式性能更好:
let charactersToRemove: Set = ["<", ">", " "]
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:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          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:@"%02x", tokenBytes[i]&0x000000FF];
}

//这个也可改成for in 循环获取

Swift:和上面方法基本一致,使用高级函数一行搞定

let token = deviceToken.map{String(format: "%02.2hhx", $0)}.joined()

let token = deviceToken.map{String(format: "%02x", $0)}.joined()

或者

let token = deviceToken.reduce("", {$0 + String(format: "%02x", $1)}) 

赏我一个赞吧~~~

你可能感兴趣的:(iOS13 DeviceToken 解析)