将deviceToken字符串转为NSData

接入新版信鸽SDK之后,出现- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(nonnull NSData *)deviceToken 不执行的问题

解决方案:
通过- (void)xgPushDidRegisteredDeviceToken:(NSString *)deviceToken error:(NSError *)error 获取到 deviceToken(NSString 类型),其他业务场景,例如活动推送、客服推送,需要使用deviceToken(NSData 类型),可以通过下面的方式来进行转换。

// 将 deviceToken NSString 类型转为 NSData 类型
    NSString *command = deviceToken;
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i = 0; i < [command length] / 2; i++) {
        byte_chars[0] = [command characterAtIndex:i * 2];
        byte_chars[1] = [command characterAtIndex:i * 2 + 1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [commandToSend appendBytes:&whole_byte length:1];
    }
    
    NSData *data = [NSData dataWithData:commandToSend];
    if (data) {
        NSLog(@"%@", data);
    }

你可能感兴趣的:(将deviceToken字符串转为NSData)