【问题标题】:UNNotificationRequest requires unique identifier, but fires on duplicates tooUNNotificationRequest 需要唯一标识符,但也会触发重复项
【发布时间】:2017-09-27 00:56:45
【问题描述】:

我这样称呼本地通知

        let center = UNUserNotificationCenter.current()
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = text
        content.categoryIdentifier = category
        content.userInfo = map
        content.sound = UNNotificationSound.default()
        content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground")
        let request = UNNotificationRequest(identifier: "testing", content: content, trigger: nil)
        center.add(request)

每次使用相同的 UNNotificationRequest 标识符(一个不变的字符串)。根据文档

标识符

请求的唯一标识符(如果标识符不唯一,则不会创建新的通知请求对象)。您可以稍后使用此标识符来取消仍待处理的请求。此参数不能为 nil。

https://developer.apple.com/documentation/usernotifications/unnotificationrequest/1649633-init

每次我触发本地通知时都会触发它,即使在应用程序的同一个实例中也是如此。标识符始终相同。文档有误吗?

【问题讨论】:

  • 你不应该重复使用相同的标识符。
  • 我知道这是不好的做法,而且我不在生产代码中。但是在测试过程中,我看到的与文档相矛盾,因为他们说“未创建对象”,但在同一标识符上发送了一个新通知。
  • 确保取消之前的预定通知
  • 不知道那个^链接如何回答我关于为什么使用相同的标识符两次仍然有效的问题。

标签: ios swift notifications ios10 ios11


【解决方案1】:

此时文档已更正且更准确: https://developer.apple.com/documentation/usernotifications/unnotificationrequest/1649633-init

系统使用标识符参数来确定如何处理 请求:

  • 如果您提供唯一标识符,系统会创建一个新通知。
  • 如果标识符与之前发送的通知匹配,系统会再次提醒用户,将旧通知替换为 新通知,并将新通知置于列表顶部。
  • 如果标识符与待处理请求匹配,则新请求将替换待处理请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-13
    • 2013-10-01
    • 2011-11-08
    • 1970-01-01
    相关资源
    最近更新 更多