问题
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 UIApplicationDelegat
e 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