一直以來使用的解析方式(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<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:@"%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 循環(huán)獲取
Swift:和上面方法基本一致朦乏,使用高級函數(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)})
賞我一個贊吧~~~