Get device token for push notification

I am working on push notifications. I wrote the following code to get the device token.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. // Add the view controller 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); } 

I can successfully run the application on the device, but could not get the device identifier on the console.

I have no problems with certification and training profiles.

+70
ios iphone push-notification apple-push-notifications appdelegate
Jan 10 2018-12-12T00:
source share
13 answers

NOTE. The solution below does not work on iOS 13+ devices anymore - it returns garbage data .

Please use the following code:

 + (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]; } 



Solution that worked before iOS 13:

Objective-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); } 

Swift 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)") } 
+138
Jan 10 2018-12-12T00:
source share

To get a Token Device, you can take several steps :

1) Enable APNS (Apple Push Notification Service) for developer certification and certification distribution, then reload these two files.

2) Download the Provisioning Developer and Distribute Provisioning file again.

3) Settings for PROJECT and TARGETS with two file settings are loaded in the Xcode interface.

4) Finally, you need to add the code to the AppDelegate file to get the Token Device (note: run the application on a real device).

 - (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); } 
+13
27 '13 at 3:56
source share

The following code is used to retrieve a device token.

  // 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); 
+6
Jan 10 2018-12-12T00:
source share

And a quick version of Wasif answer:

Swift 2.x

 var token = deviceToken.description.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "<>")) token = token.stringByReplacingOccurrencesOfString(" ", withString: "") print("Token is \(token)") 

Update for Swift 3

 let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() 
+5
Aug 30 '16 at 12:33
source share

If you still do not receive the device token, try entering the following code to register your device for push notification.

It will also work on ios8 or more.

 #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 
+4
Apr 10 '15 at 9:50
source share

Starting with iOS 13, Apple changed the output of [deviceToken description] . Now this is so {length=32,bytes=0x0b8823aec3460e1724e795cba45d22e8...af8c09f971d0dabc} , which is not true for the device token.

I suggest using this piece of code to solve the problem:

 + (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]; } 

This will work for iOS13 and below.

+2
Sep 10 '19 at 7:21
source share

In your AppDelegate, in the didRegisterForRemoteNotificationsWithDeviceToken method:

Updated for Swift:

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("\(deviceToken.reduce("") { $0 + String(format: "%02.2hhx", arguments: [$1]) })") } 
+1
Nov 26 '14 at 5:09
source share

Get device token in Swift 3

 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) print("Device token: \(deviceTokenString)") } 
+1
Nov 29 '16 at 22:09
source share

Goal C for iOS 13+ , provided by Vasif Saud

Copy the code below into AppDelegate.m and print the device’s 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); } 
+1
Sep 28 '19 at 19:59
source share

In the build setup, set the Provision Profile signature code, if you have an APN Enable certificate, then you will definitely get the token identifier. and delete

Profile Profile: Automatically

and install

Profile Profile: Collateral Profile Certificate.

0
Oct 31 '15 at 2:04
source share

Get device token in quick mode 3

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = String(format: "%@", deviceToken as CVarArg).trimmingCharacters(in: CharacterSet(charactersIn: "<>")).replacingOccurrences(of: " ", with: "") print(token) } 
0
Apr 03 '17 at 12:58 on
source share

Using description , as many of these answers suggest, is the wrong approach - even if you make it work, it will break in iOS 13+.

Instead, you should make sure that you are using real binary data, not just a description of it. Andrei Gagan approached Objective-C solution pretty well, but, fortunately, it is much simpler:

Swift 4.2 works on 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() 
0
Sep 17 '19 at 13:37
source share

To get a device token, use the following code, but you can only get a device token using a physical device. If you have the mandatory sending of a device token, then when using the simulator, you can set the condition below.

  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"]; } 
-2
Dec 28 '17 at 13:29
source share



All Articles