How to use UNNotificationPresentationOptions

我们两清 提交于 2019-12-23 01:29:26

问题


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


回答1:


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



回答2:


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.
}
}


来源:https://stackoverflow.com/questions/39868193/how-to-use-unnotificationpresentationoptions

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