Funnybear Funnybear - 1 year ago 280
Objective-C Question

iOS 10 Request Notification Permission fires twice

When I launch my app on iOS 10, I get the request notification permission twice.
The first one briefly appears and disappears immediately, then I got the second popup that wait for "allow" or "deny".

Here is my code that worked well before iOS 10.

In the method didFinishLaunchingWithOptions from the AppDelegate :

if ([application respondsToSelector:@selector(registerUserNotificationSettings:)]) {
#ifdef __IPHONE_8_0

UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIRemoteNotificationTypeBadge
|UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
} else {
UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound;
[application registerForRemoteNotificationTypes:myTypes];

Should I implement something specificaly for iOS 10 or the define __IPHONE_8_0 still works for iOS 10 ?

Answer Source

For iOS 10 we need to call the UNUserNotificationCenter in appDelegate didFinishLaunchingWithOptions method.

First we must import the UserNotifications framework and add the UNUserNotificationCenterDelegate in Appdelegate


#import <UIKit/UIKit.h>
#import <UserNotifications/UserNotifications.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@property (strong, nonatomic) UIWindow *window;



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
   if([[[UIDevice currentDevice]systemVersion]floatValue]<10.0)
      [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound |    UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
      [[UIApplication sharedApplication] registerForRemoteNotifications];
      UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
      center.delegate = self;
      [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
         if( !error )
             [[UIApplication sharedApplication] registerForRemoteNotifications];
             NSLog( @"Push registration success." );
             NSLog( @"Push registration FAILED" );
             NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
             NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );  
  return YES;

For more details

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download