有没有办法在新通知到达时删除已发送的通知?

Is there any way to remove delivered notifications upon arrival of a new one?

大约在去年第三季度,我能够使用 UNNotificationServiceExtension 不仅解密传入的推送通知内容(一个常见的用例),而且每次收到新通知时都能删除以前发送的通知.

我使用 UNUserNotificationCenter.current().getDeliveredNotifications 检索已发送的通知,然后删除我需要删除的通知。

然而,随着新的一年的到来,我突然注意到我的应用程序不再从通知中心删除以前发送的通知,尽管代码仍然存在于服务扩展中并且没有抛出任何错误,尽管服务扩展中的其他代码工作正常。

经过调试,我发现 UNUserNotificationCenter.current().getDeliveredNotifications 现在 returns 一个空的通知数组,即使在锁定屏幕上有多个通知也是如此。

UNUserNotificationCenter.current().removeAllDeliveredNotifications() 什么都不做,所以即使只是使用那个调用,不检索或过滤传递的通知,也不会删除任何东西。

有谁知道是否还有办法做到这一点?

或者 Apple 可能禁止了此功能?

看来 apns-collapse-id APNs 请求 header 在这里可能会有用。

  1. 可以用来更新之前的通知内容,并置顶

    Multiple notifications with the same collapse identifier are displayed to the user as a single notification.

  2. 根据docsapns-collapse-id指定通知identifier(通常是随机的)。 BE 可以发送一个新的 "delete" 通知,在有效载荷中使用给定的 id,以便在 removeDeliveredNotifications(withIdentifiers:) 函数中使用它。