问题描述
在 iOS 13 之前的版本使用下面代码可以将获取到的 deviceToken,转为 NSString 类型,并去掉其中的空格和尖括号,作为参数传入 setDeviceToken: 方法中。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [deviceToken description];
token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
[[RCIMClient sharedRCIMClient] setDeviceToken:token];
}
但是上面这段代码在 iOS 13 上已经无法获取准确的 deviceToken 了,iOS 13 的设备通过 [deviceToken description]
获取的内容如下:
{length=32,bytes=0xfe270338e80825d6c5d1754096f916b8...0d19a5d5834cff75}
解决方案
方法一:SDK 已升级到 2.9.25 版本,可以使用下面方法(setDeviceTokenData)直接传入 NSData 类型的 deviceToken
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[RCIMClient sharedRCIMClient] setDeviceTokenData:deviceToken];
}
方法二:SDK 未升级到 2.9.25 版本,可以修改为下面代码获取并设置 deviceToken(适配新旧系统)
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *token = [self getHexStringForData:deviceToken];
[[RCIMClient sharedRCIMClient] setDeviceToken:token];
}
- (NSString *)getHexStringForData:(NSData *)data {
NSUInteger len = [data length];
char *chars = (char *)[data bytes];
NSMutableString *hexString = [[NSMutableString alloc] init];
for (NSUInteger i = 0; i < len; i ++) {
[hexString appendString:[NSString stringWithFormat:@"%0.2hhx", chars[i]]];
}
return hexString;
}
或者:
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
const unsigned *tokenBytes = [deviceToken bytes];
if (tokenBytes == NULL) {
return;
}
NSString *token = [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])];
[[RCIMClient sharedRCIMClient] setDeviceToken:token];
}
Swift 处理方法:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var deviceTokenString = String()
let bytes = [UInt8](deviceToken)
for item in bytes {
deviceTokenString += String(format: "%02x", item&0x000000FF)
}
RCIMClient.shared()?.setDeviceToken(deviceTokenString)
}