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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32430918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:32:37  来源:igfitidea点击:

how to get Device Token in iOS?

iosobjective-cswiftdevicetoken

提问by imjaydeep

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

采纳答案by imjaydeep

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

}
) }.joined() }

回答by NANNAV

Try this code :

试试这个代码:

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

Note : simulator not return deviceToken, deviceToken only return in device with valid APNS certificate

注意:模拟器不返回 deviceToken,deviceToken 只在有有效 APNS 证书的设备中返回

回答by SomeGuy

In iOS 8 and iOS 9 you need to register for notifications like this:

在 iOS 8 和 iOS 9 中,您需要注册这样的通知:

Targets -> Capabilities -> Push Notifications

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 上调用现有代码。

回答by Sreenath S

Enable "Push Notifications" in Xcode, this will fix the issue.

在 Xcode 中启用“推送通知”,这将解决问题。

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

Attached image for reference

附上图片供参考

Note:Provisioning ProfilesShould be in ActiveState

注意:配置文件应处于活动状态

回答by Viraj Padsala

Same issue happened with me So You have to use following code to get 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)
}

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。

回答by Ved Rauniyar

Get device tokenin Swift 3

获取device token斯威夫特3

##代码##