根据苹果的指南,它建议以这种方式注册通知:
- (void)applicationDidFinishLaunching:(UIApplication *)app {
// other setup tasks here....
// Register the supported interaction types.
UIUserNotificationType types = UIUserNotificationTypeBadge |
UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings =
[UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];
// Register for remote notifications.
[[UIApplication sharedApplication] registerForRemoteNotifications];
}
如上所示,它在
registerForRemoteNotifications
之后立即调用 registerUserNotificationSettings
,但是当应用程序第一次打开时,它不会成功获取访问令牌,因为用户尚未授予通知权限。
这样,应用程序在第二次打开时就会获得访问令牌。
苹果为什么这么建议?
我建议在registerForRemoteNotifications
中调用
didRegisterUserNotificationSettings
,因为它会在用户授予通知权限后调用。
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings){
application.registerForRemoteNotifications()
}
我的建议正确吗?
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
if (notificationSettings.types != UIUserNotificationTypeNone) {
//register to receive notifications
[application registerForRemoteNotifications];
} else {
// same as response to didFailToRegisterForRemoteNotificationsWithError
NSDictionary* data = [NSDictionary dictionaryWithObject:@"" forKey:@"deviceToken"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationsRegistered" object:self userInfo:data];
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("Got token data! \(deviceToken)")
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Couldn't register: \(error)")
}
如果您想检查通知设置,请使用此方法:
func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings){
}
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .badge, .sound]
) { (granted, error) in
if granted {
getNotificationSettings()
}
}
使用此函数getNotificationSettings(),在用户允许从我们的应用程序获取通知后立即调用registerForRemoteNotifications():
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { settings in
print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
print("done with registerForRemoteNotifications()")
}
}
}
来源:https://www.kodeco.com/11395893-push-notifications-tutorial-getting-started?page=2(另请检查第一页)