如何使用UNNotificationPresentationOptions

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

但我找不到任何关于如何使用它的示例,请提出一些有关如何实现此function的建议

我已经实现了前台通知

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

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

UNUserNotificationCenterDelegate协议:

userNotificationCenter(_:didReceive:withCompletionHandler:)

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

userNotificationCenter(_:willPresent:withCompletionHandler:)

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

两种方法。 更好的是,现在他们已经被移植到他们自己的协议iOS 10中了

UNUserNotificationCenterDelegate所以这将有助于清理现有的UIApplicationDelegat e,因为它能够将所有旧的通知处理代码重构为一个shiny的,新的,有凝聚力的协议。

这是一个例子:

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