Funnybear Funnybear - 2 months ago 69
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
|UIRemoteNotificationTypeSound
|UIRemoteNotificationTypeAlert) categories:nil];
[application registerUserNotificationSettings:settings];
#endif
} 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

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

AppDelegate.h

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

@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m

- (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];
   }
   else
   {
      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." );
         }
         else
         {
             NSLog( @"Push registration FAILED" );
             NSLog( @"ERROR: %@ - %@", error.localizedFailureReason, error.localizedDescription );
             NSLog( @"SUGGESTIONS: %@ - %@", error.localizedRecoveryOptions, error.localizedRecoverySuggestion );  
         }  
     }];  
   }
  return YES;
}

For more details