如何识别UNUserNotificationCenter是来的(:didReceive)



这里我使用UNUserNotificationCenter来反复触发通知。当通知被触发时,我遇到了一个问题,我想在没有操作的情况下调用函数。有人能告诉我怎么做吗?

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print(" Foreground Notification IS CALLED ")
completionHandler([.badge, .banner, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print(" Nikan Did recieve calling ")
if response.actionIdentifier == "Okay" {
print(" Notification Clickced ")
}
completionHandler()
}
func createNotification() {
let content = UNMutableNotificationContent()
content.title = "Notification"
content.subtitle = "Wow, Notification"
content.categoryIdentifier = "Actions"
content.sound = UNNotificationSound.defaultRingtone
// show this notification five seconds from now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
// notification actions
let okay = UNNotificationAction(identifier: "Okay", title: "Okay", options: .destructive)
let category = UNNotificationCategory(identifier: "Actions", actions: [okay], intentIdentifiers: [], options: [])
UNUserNotificationCenter.current().setNotificationCategories([category])
//    UNUserNotificationCenter.current().add(request)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if let error = error {
// Something went wrong
print(error)
}
})
}

我想要一个答案,当UNUserNotificationCenter的通知被触发时调用一个函数。

问题:当收到通知时如何调用函数?

回答:当你收到notification (:didReceive), post NSNotification并在你的UIViewController中观察它。在observer的# selector方法中调用该函数。

DidReceive触发当点击推送通知,在你的情况下,应用程序是在后台,如果应用程序是打开点击推送通知,那么DidReveive将被触发。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let pushInfo = response.notification.request.content.userInfo
// post NSNotification here
// You also have data fetched from push notification (if any) in pushInfo variable
}

最新更新