iosobjective-cswiftdevicetoken

how to get Device Token in iOS?


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

-(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(@"This is device token%@", deviceToken);
    }

-(void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err
 { 
        NSString *str = [NSString stringWithFormat: @"Error: %@", err];
        NSLog(@"Error %@",err);    
 }

Solution

  • Here is the latest code of swift 4.0, so you can use following code to get device token.

    import UserNotifications
    
    if #available(iOS 10, *) {
                UNUserNotificationCenter.current().delegate = self
                UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){ (granted, error) in
                }
                UIApplication.shared.registerForRemoteNotifications()
            } else {
                UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil))
                UIApplication.shared.registerForRemoteNotifications()
            }
    
    
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
            let token = deviceToken.map { String(format: "%.2hhx", $0) }.joined()
    
        }