跳转到主要内容
PRODUCT DOCUMENTS

快速找到所需文档,高效完成接入与排障

浏览产品文档与友盟 Skill,展开目录并阅读正文。

iOS端如何获取Device Token?

iOS 端获取 Device Token 的方法如下:

开发环境获取方法:

在 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 回调函数中,添加以下代码:

objective-c

#include <arpa/inet.h>

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    if (![deviceToken isKindOfClass:[NSData class]]) return;
    
    const unsigned *tokenBytes = (const unsigned *)[deviceToken bytes];
    NSString *hexToken = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    
    NSLog(@"deviceToken: %@", hexToken);
    
    // 自 1.2.7 版本起,SDK 会自动注册 Device Token,无需手动调用注册接口
    // 如果需要手动注册,请确保传入的 token 是系统回调中的 deviceToken 参数,否则可能导致无法收到通知
    // [[UMessage shared] registerDeviceToken:deviceToken];
}

通过上述代码,可以在控制台输出一个长度为 64 位的 Device Token 字符串。

注意事项:

  • 在调用 Push SDK 的 + (void)registerDeviceToken:(NSData * __nullable)deviceToken 接口时,请确保传入的是系统回调函数 - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken 中的 deviceToken 参数。传入错误可能导致无法接收到通知消息。

生产环境获取方法:

生产环境下获取 Device Token 的方式与开发环境相同,但需要借助抓包工具或代理工具来获取 device_token。此外,也可以通过查看 NSUserDefaults 中 kUMessageUserDefaultKeyForDeviceToken 的值来获取。

相关文档:【iOS版】获取device token方法