푸시 알림을위한 장치 토큰 가져 오기
푸시 알림 작업 중입니다. 장치 토큰을 가져 오기 위해 다음 코드를 작성했습니다.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
// Add the view controller's view to the window and display.
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"This is device token%@", deviceToken);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: @"Error: %@", err];
NSLog(@"Error %@",err);
}
장치에서 응용 프로그램을 성공적으로 실행할 수 있지만 콘솔에서 장치 ID를 가져올 수 없습니다.
인증 및 프로비저닝 프로파일에 문제가 없습니다.
참고 : 아래 솔루션은 더 이상 iOS 13 이상 기기에서 작동하지 않으며 가비지 데이터를 반환합니다 .
대신 다음 코드를 사용하십시오.
+ (NSString *)hexadecimalStringFromData:(NSData *)data
{
NSUInteger dataLength = data.length;
if (dataLength == 0) {
return nil;
}
const unsigned char *dataBuffer = (const unsigned char *)data.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
return [hexString copy];
}
iOS 13 이전에 작동했던 솔루션 :
목표 -C
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"this will return '32 bytes' in iOS 13+ rather than the token", token);
}
스위프트 3.0
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
let tokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("this will return '32 bytes' in iOS 13+ rather than the token \(tokenString)")
}
토큰 장치를 얻으려면 몇 가지 단계를 수행 할 수 있습니다 .
1) 개발자 인증 및 배포 인증 모두에 대해 APNS (Apple Push Notification Service)를 활성화 한 다음이 두 파일을 다시 다운로드합니다.
2) 개발자 프로비저닝 및 배포 프로비저닝 파일을 모두 다시 다운로드합니다.
3) Xcode 인터페이스 : 두 개의 파일 프로비저닝이있는 PROJECT 및 TARGETS에 대한 프로비저닝 설정이 다운로드됩니다.
4) 마지막으로 AppDelegate 파일에 아래 코드를 추가하여 토큰 장치를 가져와야합니다 (참고 : 실제 장치에서 앱 실행).
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"%@", str);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: @"Error: %@", err];
NSLog(@"%@",str);
}
다음 코드는 장치 토큰 검색에 사용됩니다.
// Prepare the Device Token for Registration (remove spaces and < >)
NSString *devToken = [[[[deviceToken description]
stringByReplacingOccurrencesOfString:@"<"withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
NSString *str = [NSString
stringWithFormat:@"Device Token=%@",devToken];
UIAlertView *alertCtr = [[[UIAlertView alloc] initWithTitle:@"Token is " message:devToken delegate:self cancelButtonTitle:nil otherButtonTitles: nil] autorelease];
[alertCtr show];
NSLog(@"device token - %@",str);
그리고 Wasif의 대답의 Swift 버전 :
스위프트 2.x
var token = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>"))
token = token.stringByReplacingOccurrencesOfString(" ", withString: "")
print("Token is \(token)")
Swift 3 업데이트
let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
여전히 디바이스 토큰을받지 못하는 경우 다음 코드를 입력하여 푸시 알림에 디바이스를 등록하십시오.
ios8 이상에서도 작동합니다.
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000
if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
[[UIApplication sharedApplication] registerForRemoteNotifications];
} else {
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
}
#else
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound];
#endif
iOS 13부터 Apple은 [deviceToken description]
출력 을 변경했습니다 . 이제 이것은 {length=32,bytes=0x0b8823aec3460e1724e795cba45d22e8...af8c09f971d0dabc}
장치 토큰에 대해 잘못된 것입니다.
이 코드 조각을 사용하여 문제를 해결하는 것이 좋습니다.
+ (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];
}
iOS13 이하에서 작동합니다.
Swift 3에서 장치 토큰 가져 오기
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device token: \(deviceTokenString)")
}
AppDelegate의 didRegisterForRemoteNotificationsWithDeviceToken
메서드에서 :
Swift 업데이트 :
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("\(deviceToken.reduce("") { $0 + String(format: "%02.2hhx", arguments: [$1]) })")
}
Objective C for iOS 13+, courtesy of Wasif Saood's answer
Copy and paste below code into AppDelegate.m to print the device APN token.
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
NSUInteger dataLength = deviceToken.length;
if (dataLength == 0) {
return;
}
const unsigned char *dataBuffer = (const unsigned char *)deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendFormat:@"%02x", dataBuffer[i]];
}
NSLog(@"APN token:%@", hexString);
}
In a build setting set code signing Provision Profile if you have APN Enable certificate then you will definitely get the token id. and remove
Provision Profile : Automatic
and set to
Provision Profile : Your provision profile certificate.
Using description
as many of these answers suggest is the wrong approach - even if you get it to work, it will break in iOS 13+.
Instead you should ensure you use the actual binary data, not simply a description of it. Andrey Gagan addressed the Objective C solution quite well, but fortunately it's much simpler in swift:
Swift 4.2 works in iOS 13+
// credit to NSHipster (see link above)
// format specifier produces a zero-padded, 2-digit hexadecimal representation
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
In order to get the device token use following code but you can get the device token only using physical device. If you have mandatory to send the device token then while using simulator you can put the below condition.
if(!(TARGET_IPHONE_SIMULATOR))
{
[infoDict setValue:[[NSUserDefaults standardUserDefaults] valueForKey:@"DeviceToken"] forKey:@"device_id"];
}
else
{
[infoDict setValue:@"e79c2b66222a956ce04625b22e3cad3a63e91f34b1a21213a458fadb2b459385" forKey:@"device_id"];
}
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
NSLog(@"My token is: %@", deviceToken);
NSString * deviceTokenString = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""] stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"the generated device token string is : %@",deviceTokenString);
[[NSUserDefaults standardUserDefaults] setObject:deviceTokenString forKey:@"DeviceToken"];
}
참고URL : https://stackoverflow.com/questions/8798725/get-device-token-for-push-notification
'Nice programing' 카테고리의 다른 글
XAML에서 컨트롤 중심을 회전하는 방법 (0) | 2020.10.31 |
---|---|
사용자 정의 함수에 도구 설명을 추가하는 방법 (0) | 2020.10.31 |
CMake로 컴파일러의 C ++ 11 지원을 감지하는 방법 (0) | 2020.10.31 |
함수의 PHP 액세스 전역 변수 (0) | 2020.10.31 |
간단한 파이프로 소수점 2 자리로 제한 (0) | 2020.10.31 |