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

7
我有一个触发器可以向用户显示通知:
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)

一旦设置了触发器,您是否有办法取消它?

如何在时间间隔结束之前取消通知并调用通知?


你问这个的意思是什么?系统只计算活动通知。 - Mannopson
@Mannopson 我想问,假设我打开了一个触发器,在15分钟后显示本地通知,但在10分钟后我想取消该触发器以不显示通知,我该怎么做? - Chief Madog
使用 removePendingNotificationsWithIdentifier 方法。您可以通过给定的标识符取消通知。 - Mannopson
@Mannopson,你能把那个写成答案吗?我会给你正确的答案。 - Chief Madog
可能是删除特定本地通知的重复问题。 - Cœur
2个回答

16

您可以通过调用以下方法取消或删除通知:

let center = UNUserNotificationCenter.current()

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

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

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

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

0

在 Mannopson 的回答基础上进行扩展:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接