Search code examples
iosios8push-notificationapple-push-notificationsios9

calling registerForRemoteNotifications immediately after registerUserNotificationSettings?


According to apple's guide it suggests to register for notifications this way:

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

As shown above, it calls registerForRemoteNotifications immediately after registerUserNotificationSettings , but when the application is opened for the first time it wont succeed to get the access token because the user hasn't granted notification permission yet.

In this way, the application will get the access token just if it was opened for the second time.

Why does apple suggest that?

What I suggest is calling registerForRemoteNotifications in didRegisterUserNotificationSettings because it will be called after the user grant notification permission.

   func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings){


       application.registerForRemoteNotifications()

    }

Is my suggestion correct ?


Solution

  • Your suggestion is correct. You may always want to post an NSNotification is you want to handle the failure in your view controller.

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