как получить токен устройства в iOS?

Я работаю над push-уведомлениями. Я написал следующий код для получения токена устройства.

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

person imjaydeep    schedule 07.09.2015    source источник
comment
возможный дубликат Получить токен устройства для push-уведомления   -  person Yuyutsu    schedule 07.09.2015


Ответы (6)


Попробуйте этот код:

 // Register for Push Notification


 if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
    }

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings // NS_AVAILABLE_IOS(8_0);
{
        [application registerForRemoteNotifications];
    }

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{

    NSLog(@"deviceToken: %@", deviceToken);
    NSString * token = [NSString stringWithFormat:@"%@", deviceToken];
    //Format token as you need:
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
    token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];

}

Примечание: симулятор не возвращает deviceToken, deviceToken возвращает только устройство с действительным сертификатом APNS.

person NANNAV    schedule 07.09.2015
comment
Ваша заметка, я думаю, недооценена, я бы выделил ее, так как это решило мою большую проблему. - person C. Skjerdal; 12.01.2019

Включите «Push-уведомления» в Xcode, это решит проблему.

Targets -> Capabilities -> Push Notifications

Прикрепленное изображение для справки

Примечание. Профили подготовки должны быть в состоянии Активен.

person Sreenath S    schedule 13.03.2017

В iOS 8 и iOS 9 вам необходимо зарегистрироваться для получения уведомлений следующим образом:

NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];

Обратите внимание: если вы также хотите поддерживать iOS 7, вам нужно будет вызывать существующий код в более ранних версиях iOS.

person SomeGuy    schedule 07.09.2015

Та же проблема произошла со мной, поэтому вам нужно использовать следующий код, чтобы получить токен устройства: -

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 
{
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"content---%@", token);
} 

Даже в этом случае это не сработает. Затем проверьте свой профиль обеспечения, он должен иметь тот идентификатор приложения, с помощью которого вы создали свой ssl-сертификат для push-уведомлений.

person Viraj Padsala    schedule 07.09.2015

Вот последний код swift 4.0, поэтому вы можете использовать следующий код для получения токена устройства.

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

    }
person imjaydeep    schedule 12.07.2018

Получите device token в Swift 3

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = String(format: "%@", deviceToken as CVarArg)
        .trimmingCharacters(in: CharacterSet(charactersIn: "<>"))
        .replacingOccurrences(of: " ", with: "")
    print(token)
}
person Ved Rauniyar    schedule 03.04.2017