Friday 7 October 2016

Push notification in iOS10

With the introduction of iOS10 and xcode8 there are some changes in the way push notification works.
In iOS10 we may get  an errors from didFailToRegisterForRemoteNotificationsWithError . If you get following error in iOS10 but not in iOS9 then you will need to enable push entitlements locally.




1) In targets, under capabilities enable push notification to add push notification entitlements .


2) Add UserNotifications.framework into your app. Import UserNotification.framework in your AppDelegate.

#import <UserNotifications/UserNotifications.h>

@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end


3) Now to register push notification in iOS10 , add following code in didFinishLaunchingWithOptions method,

if (SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")) {       UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){
            if( !error ){
                [[UIApplication sharedApplication] registerForRemoteNotifications];
            }
        }];
    
    }

4) Now implement delegate methods of UNUserNotificationCenterDelegate:

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    
    //Called when a notification is delivered to a foreground app.
    
    NSLog(@"Userinfo %@",notification.request.content.userInfo);
    
    completionHandler(UNNotificationPresentationOptionAlert);
}

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    //Called to let your app know which action was selected by the user for a given notification.
    
    NSLog(@"Userinfo %@",response.notification.request.content.userInfo);
    
}



Reference: http://stackoverflow.com/questions/39490605/push-notification-issue-with-ios-10