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: "")

//當(dāng)然下面這種方式性能更好:
let charactersToRemove: Set<Character> = ["<", ">", " "]
let tokenNew = dataStr.description.removeAll(where: charactersToRemove.contains)

或者類似的解析方式,都是替換< >空字符串這種方法.

在stackoverflow中有人說過這樣的解析方式并不好,但是一直沒有問題,所以大家也就習(xí)慣了這樣的解析方式了,但是iOS13中這樣的解析方式就有問題了
大家可以更新解析方式為下面這樣的方式(兼容各個(gè)版本):
Objective-C: (這個(gè)是友盟提供的方法)

- (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];
}

//這個(gè)也可改成for in 循環(huán)獲取

Swift:和上面方法基本一致,使用高級(jí)函數(shù)一行搞定

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)}) 

賞我一個(gè)贊吧~~~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容