How to use UNNotificationPresentationOptions

泪湿孤枕 提交于 2019-12-08 08:29:28

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")
            }            
        }

The new iOS 10 UNUserNotificationCenterDelegate now has a single set of methods for handling both remote and local notifications.

UNUserNotificationCenterDelegate protocol:

userNotificationCenter(_:didReceive:withCompletionHandler:)

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

userNotificationCenter(_:willPresent:withCompletionHandler:)

Delivers a notification to an app running in the foreground.

Two methods. And what’s better, is that now that they are moved into their own protocol, the iOS 10

UNUserNotificationCenterDelegate so this will help clean up your existing UIApplicationDelegate by being able to refactor all that old notification handling code into a shiny, new, cohesive protocol of it’s own.

Here’s an example:

extension NotificationManager: UNUserNotificationCenterDelegate {

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

    switch response.actionIdentifier {

    // NotificationActions is a custom String enum I've defined
    case NotificationActions.HighFive.rawValue:
        print("High Five Delivered!")
    default: break
    }
}

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {

    // Delivers a notification to an app running in the foreground.
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!