Search code examples
iosiphonepush-notificationapple-push-notificationsappdelegate

Get device token for push notification


I am working on push notifications. I wrote the following code for fetching a device token.

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

I am able to run application on device successfully but not able to get the device id on console.

I have no issues with certification and provisioning profiles.


Solution

  • NOTE: The below solution no longer works on iOS 13+ devices - it will return garbage data.

    Please use following code instead:

    + (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 prior to 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)")
    }