如何在Swift中取消本地通知触发器

时间:2019-03-24 14:15:01

标签: swift unusernotificationcenter unnotificationrequest

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

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用完并取消通知之前取消通知?

2 个答案:

答案 0 :(得分:2)

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

let center = UNUserNotificationCenter.current()

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

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

并删除具有给定标识符的已发送通知

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

答案 1 :(得分:0)

以曼诺普森的答案为基础:

这会删除所有待处理的通知( Swift 5

func cancelNotifications() -> Void {
    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}