首页 > 解决方案 > 如何在 Swift 中取消本地通知触发器

问题描述

我有一个触发器向用户显示通知:

let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 20, repeats: false)

let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

有没有办法让我在设置触发器后取消它?

如何在timeInterval用完之前取消通知并调用通知?

标签: swiftunusernotificationcenterunnotificationrequest

解决方案


您可以通过以下方式取消或删除通知:

let center = UNUserNotificationCenter.current()

删除具有给定标识符的待处理通知

center.removePendingNotificationRequests(withIdentifiers: [“givenIdentifier”])

并删除具有给定标识符的已传递通知

center.removeDeliveredNotifications(withIdentifiers: [“givenIdentifier”])

推荐阅读