david david - 5 months ago 66
iOS Question

calling registerForRemoteNotifications immediately after registerForRemoteNotifications?

according to apple guide it suggest to register for notifications in 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 you can see 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 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()

}


does my suggestion correct ?

Answer

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