在这里,我使用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的通知时,我需要一个响应来调用一个函数。
发布于 2022-12-01 05:27:44
问:当收到通知时,如何调用函数?
答:当你收到通知时(:in ),发布NSNotification并在你的UIViewController中观察它。在观察者的#selecteor方法中调用函数。
当点击推送通知时,DidReceive会触发,在您的情况下,应用程序处于后台,如果应用程序是通过单击push通知打开的,那么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
}https://stackoverflow.com/questions/74623515
复制相似问题