[IOS] objective-c 아이폰 디바이스 토큰(device notification token) 가져오기
IOS 13 미만에서는 device notification token 을 가져올 경우 아래와 같은 형태였다.
<124686a5 556a72ca d808f572 00c323b9 3eff9285 92445590 3225757d b83997ba>
여기서 특수문자 <, >, 그리고 띄어쓰기를 제거해서 사용하면 됐다.
IOS 13 이상에서는 device notification token 을 가져오면 아래와 같은 형태로 나온다.
{ length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f … 28f10282 14af515f }
IOS 13 이상에서 제대로 된 device notification token 문자열을 가져오려면 NSData 타입의 deviceToken 변수로 NSString 을 얻어내야 한다. 코드는 다음과 같다.
|
-(NSString *)stringFromDeviceToken:(NSData *)deviceToken { NSUInteger length = deviceToken.length; if (length == 0) { return nil; } const unsigned char *buffer = deviceToken.bytes; NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)]; for (int i = 0; i < length; ++i) { [hexString appendFormat:@”%02x”, buffer[i]]; } return [hexString copy]; } |
실제 코드 수정은 기존 코드를 살리는 방식으로 했다.
(1) 기존 코드로 디바이스 토큰을 가져오되 (2) 가져온 디바이스 토큰이 length 라는 문자열을 포함할 경우 stringFromDeviceToken 메서드를 사용하도록 수정했다. 코드는 다음과 같다.
|
// bb_ 200527 ios13 이상에서 디바이스 토큰 가져오지 못하는 오류 수정 #define contains(str1, str2) ([str1 rangeOfString: str2].location != NSNotFound) (중략) // bb_ 200527 ios13 이상에서 디바이스 토큰 가져오지 못하는 오류 수정 // ios13 미만 : <124686a5 556a72ca d808f572 00c323b9 3eff9285 92445590 3225757d b83997ba> // ios13 이상 : { length = 32, bytes = 0xd3d997af 967d1f43 b405374a 13394d2f … 28f10282 14af515f } if (tokenHex != nil && contains(tokenHex, @”length”)) { NSString *ios13deviceToken = [self stringFromDeviceToken:deviceToken]; NSLog(@”ios13deviceToken = %@”, ios13deviceToken); tokenHex = [ios13deviceToken mutableCopy];
// 꺽쇠 제거 및 공백 제거 if (tokenHex != nil) { [tokenHex replaceOccurrencesOfString:@”<” withString:@”” options:0 range:NSMakeRange(0, [tokenHex length])]; [tokenHex replaceOccurrencesOfString:@”>” withString:@”” options:0 range:NSMakeRange(0, [tokenHex length])]; [tokenHex replaceOccurrencesOfString:@” ” withString:@”” options:0 range:NSMakeRange(0, [tokenHex length])]; } } |