如何使用UNNotificationPresentationOptions

时间:2016-10-05 07:46:29

标签: ios swift usernotifications

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

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

2 个答案:

答案 0 :(得分:7)

我已经通过

实现了前台通知

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

    }

}

在关于didFinishLaunchingWithOptions的Appdelegate中

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

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

答案 1 :(得分:0)

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

UNUserNotificationCenterDelegate协议:

userNotificationCenter(_:didReceive:withCompletionHandler:)

要求您的应用知道用户为给定通知选择了哪个操作。

userNotificationCenter(_:willPresent:withCompletionHandler:)

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

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

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

以下是一个例子:

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