【问题标题】:How to cancel a local notification trigger in Swift如何在 Swift 中取消本地通知触发器
【发布时间】:2019-08-14 22:06:59
【问题描述】:

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

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

【问题讨论】:

  • 你问这个是什么意思?系统只计算活动通知。
  • @Mannopson 我问,假设我在 15 分钟内打开了一个触发器以显示本地通知,但 10 分钟后我想取消该触发器以不显示通知我该怎么做?
  • 使用removePendingNotificationsWithIdentifier。您可以通过给定的标识符取消通知。
  • @Mannopson 你能把它写成答案吗?我给你正确答案

标签: swift unusernotificationcenter unnotificationrequest


【解决方案1】:

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

let center = UNUserNotificationCenter.current()

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

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

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

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

【讨论】:

    【解决方案2】:

    以 Mannopson 的回答为基础:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多