简体   繁体   English

如何在iOS中获取设备令牌?

[英]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);    
 }

Try this code : 试试这段代码:

 // 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:@""];

}

Note : simulator not return deviceToken, deviceToken only return in device with valid APNS certificate 注意:模拟器不返回deviceToken,deviceToken仅返回具有有效APNS证书的设备

In iOS 8 and iOS 9 you need to register for notifications like this: 在iOS 8和iOS 9中,您需要注册以下通知:

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

Note that if you also want to support iOS 7, then you'll need to call your existing code on the earlier versions of iOS. 请注意,如果您还想支持iOS 7,那么您需要在早期版本的iOS上调用现有代码。

Enable " Push Notifications " in Xcode, this will fix the issue. 在Xcode中启用“ 推送通知 ”,这将解决问题。

Targets -> Capabilities -> Push Notifications

附图供参考

Note: Provisioning Profiles Should be in Active State 注意: 供应配置文件应处于活动状态

Same issue happened with me So You have to use following code to get device token:- 同样的问题发生在我身上所以你必须使用以下代码来获取设备令牌: -

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

Even then it doesn't work Then please check your provisioning profile,it should be of that app ID by which you have created your ssl certificate for push notification. 即使这样它也不起作用然后请检查您的配置文件,它应该是您为推送通知创建ssl证书的应用程序ID。

Here is the latest code of swift 4.0, so you can use following code to get device token. 这是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()

    }

Get device token in Swift 3 Swift 3中获取device token

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM