How to get an iOS deviceToken hexadecimal string

更新时间:
复制 MD 格式

Convert an iOS deviceToken to the hexadecimal string format required by the mPaaS Mobile Push Service (MPS) console.

An iOS app receives a deviceToken from the Apple Push Notification (APN) server. You must bind this deviceToken to the mPaaS push service. During development and testing, you can use the deviceToken for push tests based on the Device dimension in the Mobile Push (MPS) console. The MPS console accepts deviceTokens only in hexadecimal string format. Use the following code to obtain this string:

// For iOS versions earlier than 13, get the hex string as follows:
NSString *hexTokenString = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
hexTokenString = [hexTokenString stringByReplacingOccurrencesOfString:@" " withString:@""];
if ([hexTokenString length] > 0) {
    NSLog(@"push DeviceToken is: %@",hexTokenString);
}


// For iOS 13, get the hex string as follows:
NSUInteger dataLength = deviceToken.length;
if (dataLength == 0) {
  return;
}
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *hexTokenString  = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
  [hexTokenString appendFormat:@"%02x", dataBuffer[i]];
}
NSLog(@"push DeviceToken token:%@", hexTokenString);