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

4

我正在开发推送通知功能。我编写了以下用于获取设备令牌的代码。

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

6
可能是获取推送通知的设备令牌的重复问题。 - Yuyutsu
6个回答

15

试试这段代码:

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

}

注意:模拟器不会返回设备令牌,只有在具有有效 APNS 证书的设备中才会返回设备令牌。


我认为你的笔记被低估了,因为它解决了我的一个大问题,所以我想要强调它。 - C. Skjerdal

2

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

Targets -> Capabilities -> Push Notifications

参考附图

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


1

这里是最新的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()

    }

1
在iOS 8和iOS 9中,您需要像这样注册通知:
NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert categories:nil]];
[[UIApplication sharedApplication] registerForRemoteNotifications];

请注意,如果您还想支持 iOS 7,则需要在较早版本的 iOS 上调用您现有的代码。

1

我也遇到了同样的问题,所以你需要使用以下代码来获取设备令牌:

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

即使如此仍无法正常工作,请检查您的配置文件,它应该是用于为推送通知创建SSL证书的应用程序ID。

-1

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接