本文档介绍 iOS SDK 提供的 DeviceToken 接口,包括 DeviceToken 的上报和获取。
上报DeviceToken
为了使用阿里云移动推送服务,需将设备的 DeviceToken 上报给阿里云。首先,确保已经申请推送权限并向 APNs 注册。在成功的回调中获取到 deviceToken 后,将其上报。
详细步骤可以参考iOS SDK集成——配置APNs推送能力。
接口定义
+ (void)registerDevice:(NSData *)deviceToken
withCallback:(CallbackHandler)callback;
参数说明
参数 | 类型 | 是否必选 | 说明 |
参数 | 类型 | 是否必选 | 说明 |
deviceToken | NSData | 是 | 苹果APNs服务器返回的deviceToken。 |
callback | Block | 否 | 注册结果的回调函数。 |
使用示例
Swift
Object C
// 请求用户授权
func setupAPNs() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
DispatchQueue.main.async {
if granted {
UIApplication.shared.registerForRemoteNotifications()
}
print("推送权限状态: \(granted ? "已授权" : "被拒绝")")
}
}
}
// APNS设备注册成功回调
func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
CloudPushSDK.registerDevice(deviceToken) { result in
let status = result.success ? "成功" : "失败"
print("DeviceToken上报\(status)")
}
}
- (void)setupAPNs {
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge)
completionHandler:^(BOOL granted, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (granted) {
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
NSLog(@"推送权限状态: %@", granted ? @"已授权" : @"被拒绝");
});
}];
}
// APNS设备注册成功回调
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *result) {
NSString *status = result.success ? @"成功" : @"失败";
NSLog(@"DeviceToken上报%@", status);
}];
}
获取DeviceToken
在成功上报后,可以通过以下接口获取已上报的 DeviceToken。
接口定义
+ (NSString *)getApnsDeviceToken;
该文章对您有帮助吗?
- 本页导读 (0)
- 上报DeviceToken
- 接口定义
- 参数说明
- 使用示例
- 获取DeviceToken
- 接口定义