Push Notification displayed when application in foreground in iOS 10

P

Introduction: 

The new framework called “UserNotifications” is introduced with iOS 10 SDK. The UserNotifications framework (UserNotifications.framework) supports the delivery and handling of local and remote notifications when application is in foreground

Steps for implement code to handle push notifications in iOS 10

Import UserNotifications.framework in your AppDelegate file :                                                                              import UserNotifications  and Also add UNUserNotificationCenterDelegate.

Register for Notification :

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerForRemoteNotification()
return true
}
func registerForRemoteNotification() {
if #available(iOS 10.0, *) {
let center  = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
if error == nil{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
else {
UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
UIApplication.shared.registerForRemoteNotifications()

}

}

 Handling delegate methods for UserNotifications :
//MARK: UNUserNotificationCenter Delegate  >= iOS 10
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ UNNotificationPresentationOptions) -> Void) {

       //Called when a notification is delivered to a foreground app.

        let userInfo = notification.request.content.userInfo as? NSDictionary

         completionHandler([.alert, .badge, .sound])

        print(\(userInfo)”)

       }

  @available(iOS 10.0, *)

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        // Called to let your app know which action was selected by the user for a given notification.

        let userInfo = response.notification.request.content.userInfo as? NSDictionary
print(“\(userInfo)”)
}

      Add Push Notifications Entitlements :  Go to your project target’s Capabilities tab and add Push Notifications Entitlements. If it’s available in your     certificates then it will enable directly else configure your profile with the certificates and you can enable this capability by that.

For Detail refer the this link :
http://ashishkakkad.com/2016/09/push-notifications-in-ios-10-swift/

About the author

Pragati Rode
By Pragati Rode

Category