푸시 알림을 구현하고 있습니다. APNS 토큰을 문자열로 저장하고 싶습니다.
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
NSString *tokenString = [NSString stringWithUTF8String:[newDeviceToken bytes]]; //[[NSString alloc]initWithData:newDeviceToken encoding:NSUTF8StringEncoding];
NSLog(@"%@", tokenString);
NSLog(@"%@", newDeviceToken);
}
첫 번째 코드 줄은 null을 인쇄합니다. 두 번째는 토큰을 인쇄합니다. newDeviceToken을 NSString으로 어떻게 얻을 수 있습니까?
답변
이것을 사용하십시오 :
NSString * deviceTokenString = [[[[deviceToken description]
stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"The generated device token string is : %@",deviceTokenString);
답변
누군가 Swift 에서이 작업을 수행하는 방법을 찾고 있다면 :
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
var tokenString = ""
for i in 0..<deviceToken.length {
tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
}
print("tokenString: \(tokenString)")
}
편집 : 스위프트 3
Swift 3는 Data
값 의미론을 가진 유형을 소개합니다 . 를 deviceToken
문자열 로 변환하려면 다음과 같이하십시오.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
print(token)
}
답변
누군가 나를 도와주었습니다.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
const unsigned *tokenBytes = [deviceToken bytes];
NSString *hexToken = [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])];
[[MyModel sharedModel] setApnsToken:hexToken];
}
답변
이것을 사용할 수 있습니다
- (NSString *)stringWithDeviceToken:(NSData *)deviceToken {
const char *data = [deviceToken bytes];
NSMutableString *token = [NSMutableString string];
for (NSUInteger i = 0; i < [deviceToken length]; i++) {
[token appendFormat:@"%02.2hhX", data[i]];
}
return [token copy];
}
답변
Swift 3 에서 가장 쉬운 방법 을 원하는 사람들을 위해
func extractTokenFromData(deviceToken:Data) -> String {
let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
return token.uppercased();
}
답변
%02.2hhx
높은 투표 답변 에 대한 설명 :
%
:x
변환 지정자를 소개 합니다.02
: 변환 된 값의 최소 너비는 2입니다. 변환 된 값의 필드 너비보다 바이트 수가 적은0
경우 왼쪽에 채워집니다 ..2
:x
변환 지정자 에 표시 할 최소 자릿수를 제공 합니다.hh
:x
변환 지정자가 부호있는 char 또는 부호없는 char 인수에 적용되도록 지정합니다 (인수는 정수 승격에 따라 승격되지만 값은 인쇄하기 전에 부호있는 char 또는 부호없는 char로 변환됩니다).x
: 부호없는 인수는 “dddd”스타일의 부호없는 16 진수 형식으로 변환됩니다. 문자 “abcdef”가 사용됩니다. 정밀도는 표시 할 최소 자릿수를 지정합니다. 변환되는 값을 더 적은 자릿수로 표시 할 수 있으면 앞에 오는 0으로 확장됩니다. 기본 정밀도는 1입니다. 명시 적 정밀도 0으로 0을 변환 한 결과는 문자가 아닙니다.
자세한 내용은 IEEE printf 사양을 참조하십시오 .
위의 설명을 바탕으로, 나는 변화에 더 나은 생각 %02.2hhx
을 %02x
하거나 %.2x
.
Swift 5의 경우 다음 방법을 모두 사용할 수 있습니다.
deviceToken.map({String(format: "%02x", $0)}).joined()
deviceToken.map({String(format: "%.2x", $0)}).joined()
deviceToken.reduce("", {$0 + String(format: "%02x", $1)})
deviceToken.reduce("", {$0 + String(format: "%.2x", $1)})
테스트는 다음과 같습니다.
let deviceToken = (0..<32).reduce(Data(), {$0 + [$1]})
print(deviceToken.reduce("", {$0 + String(format: "%.2x", $1)}))
// Print content:
// 000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f
답변
내 솔루션이며 내 앱에서 잘 작동합니다.
NSString* newToken = [[[NSString stringWithFormat:@"%@",deviceToken]
stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]] stringByReplacingOccurrencesOfString:@" " withString:@""];
- 변환
NSData
에NSString
와stringWithFormat
- “<>”트림
- 공백을 제거하십시오