无需输入函数 didRegisterForRemoteNotificationsWithDeviceToken 即可获取设备令牌

get device token without enter to the function didRegisterForRemoteNotificationsWithDeviceToken

我在设置页面中有一个按钮可以让用户启用或禁用推送通知。

如果用户不允许在第一次启动应用程序时接收推送通知,如果用户稍后在设置页面中打开通知设置,我如何获取设备令牌?

谢谢。

不,你不能,除非用户允许,否则你无法获取设备令牌,一旦用户允许,你必须从 didRegisterForRemoteNotificationsWithDeviceToken 回调中检索设备令牌。

如果用户第一次拒绝您的推送通知请求,直到用户在Setting.app->Privacy为您的应用启用推送通知服务,您才能获得令牌。

所以你应该检查

[[UIApplication sharedApplication] enabledRemoteNotificationTypes]

每次用户在您的应用程序中更改通知设置时,
如果结果是没有启用通知,你应该引导用户更改Setting.app->Privacy;
中的通知设置 如果结果是通知已启用,则使用此代码检索令牌:

[[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert]

这将触发 -didRegisterForRemoteNotificationsWithDeviceToken 回调。

不,这是不可能的,当用户验证 allow permission 和 运行 您的项目时,它会自动调用方法 didRegisterForRemoteNotificationsWithDeviceToken,否则它会调用 didFailToRegisterForRemoteNotificationsWithError

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:
(NSData *)deviceToken {

NSString* deviceTokene = [[[[deviceToken description]
                            stringByReplacingOccurrencesOfString: @"<" withString: @""]
                           stringByReplacingOccurrencesOfString: @">" withString: @""]
                          stringByReplacingOccurrencesOfString: @" " withString: @""] ;



NSLog(@"%@",deviceTokene);


}

这是 coding 以在 Viewcontroller

中启用 APNS
  UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge
                                                                                             |UIUserNotificationTypeSound
                                                                                             |UIUserNotificationTypeAlert) categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];

如果你想在 VC

中禁用 APNS
 [[UIApplication sharedApplication] unregisterForRemoteNotifications];