如何使用 UNNotificationPresentationOptions

How to use UNNotificationPresentationOptions

在 iOS 10 中,有一个选项可以在应用程序处于前台时使用 UNNotificationPresentationOptions,

显示通知

但我找不到任何关于如何使用它的示例,请提出一些关于如何实现此功能的想法

新的 iOS 10 UNUserNotificationCenterDelegate 现在有一组用于处理远程和本地通知的方法。

UNUserNotificationCenterDelegate 协议:

userNotificationCenter(_:didReceive:withCompletionHandler:)

调用是为了让您的应用知道用户为给定通知选择了哪个操作。

userNotificationCenter(_:willPresent:withCompletionHandler:)

向前台的应用 运行 发送通知。

两种方法。更好的是,现在他们已经进入了自己的协议,iOS 10

UNUserNotificationCenterDelegate 因此,这将有助于清理您现有的 UIApplicationDelegate,因为它能够将所有旧的通知处理代码重构为它自己的一个闪亮的、新的、有凝聚力的协议。

举个例子:

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

我已经通过

实现了前台通知

在我的 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")

    }

}

在我的 Appdelegate 中 didFinishLaunchingWithOptions

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

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