如何在 Swift 中取消本地通知触发器
How to cancel a local notification trigger in 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
用完并调用通知之前取消通知?
您可以通过调用以下方式取消或删除通知:
let center = UNUserNotificationCenter.current()
删除具有给定标识符的待处理通知
center.removePendingNotificationRequests(withIdentifiers: [“givenIdentifier”])
并删除已发送的具有给定标识符的通知
center.removeDeliveredNotifications(withIdentifiers: [“givenIdentifier”])
以 Mannopson 的回答为基础:
这将删除所有待处理的通知 (Swift 5)
func cancelNotifications() -> Void {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}
我有一个向用户显示通知的触发器:
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
用完并调用通知之前取消通知?
您可以通过调用以下方式取消或删除通知:
let center = UNUserNotificationCenter.current()
删除具有给定标识符的待处理通知
center.removePendingNotificationRequests(withIdentifiers: [“givenIdentifier”])
并删除已发送的具有给定标识符的通知
center.removeDeliveredNotifications(withIdentifiers: [“givenIdentifier”])
以 Mannopson 的回答为基础:
这将删除所有待处理的通知 (Swift 5)
func cancelNotifications() -> Void {
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
}