适配 iOS 13 设置 deviceToken

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

解决方法:

- (void)application:(UIApplication *)application
    didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    if (@available(iOS 13.0, *)) {
          NSString *token = [self getHexStringForData:deviceToken];
          NSLog(@"iOS 13之后的deviceToken的获取方式");
    } else {
        NSString *deviceTokenString = [[[[deviceToken description]
                             stringByReplacingOccurrencesOfString:@"<" withString:@""]
                            stringByReplacingOccurrencesOfString:@">" withString:@""]
                           stringByReplacingOccurrencesOfString:@" " withString:@""];
          NSLog(@"iOS 13之前的deviceToken的获取方式");
    } 
}

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

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)
        }
        // 设置deviceTokenString 并发送到服务器
    }
发布了336 篇原创文章 · 获赞 124 · 访问量 65万+

猜你喜欢

转载自blog.csdn.net/u013538542/article/details/103738374