How to use UNNotificationPresentationOptions

satheesh picture satheesh · Oct 5, 2016 · Viewed 11.2k times · Source

In iOS 10 , there is an option for presenting the notification when the app is in foreground using UNNotificationPresentationOptions,

but i couldn't find any sample on how to use this, please suggest some idea about how to implement this feature

Answer

satheesh picture satheesh · Oct 5, 2016

I have implemented the foreground notification by

Adding the below code in my viewController

extension UIViewController: UNUserNotificationCenterDelegate {

    public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
        completionHandler( [.alert, .badge, .sound])
    }

    public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
        print("Do what ever you want")

    }

}

In my Appdelegate on didFinishLaunchingWithOptions

UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound]) {(accepted, error) in

            if !accepted {   
                print("Notification access denied")
            }            
        }