首页 > 解决方案 > 如果应用程序已关闭或在后台,如何删除特定的远程通知

问题描述

我的应用程序有一个聊天服务,当收到新的通知时,我想清除 user1 和 user2 之间的通知,除了新的通知。

当应用程序在前台时,我可以通过调用:

        UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
        print("count: \(notifications.count)")
        for notif in notifications {
            let nUserInfo = notif.request.content.userInfo
            let nType = Int(nUserInfo[AnyHashable("type")] as! String)
            if nType == type {
                let notifId = notif.request.identifier
                if notifId != notification.request.identifier {
                    center.removeDeliveredNotifications(withIdentifiers: [notif.request.identifier])
                }
            }
        }

其中类型是自定义值。当应用程序在后台或被用户关闭时如何执行此操作。

标签: iosswiftpush-notificationchat

解决方案


您需要打开后台模式功能并检查远程通知模式。为了在后台删除通知,您需要发送一个没有警报的新通知,例如{"aps": {"content-available": 1}, "del-id": "1234"},其中的content-available意思(您可以在此处查看更多关于Apple 推送服务的信息)

包含这个值为 1 的键来配置后台更新通知。当此键存在时,系统会在后台唤醒您的应用程序并将通知传递给其应用程序委托。有关配置和处理后台更新通知的信息,请参阅配置后台更新通知。

并且 del-id 将是您要删除的通知的 id,您也可以使用数组。您也可以将这些信息与您的消息通知放在一起。

在您的AppDelegate.swift中,您将需要添加此方法以在后台删除通知。在您的情况下,您可以发送您不想删除的通知的 id,并使用您的方法删除所有已发送的通知,除了您在上一次通知中发送的 id 的通知。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    guard let idToDelete = userInfo["del-id"] as? String else {
        completionHandler(.noData)
        return
    }

    UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [idToDelete])
    completionHandler(.noData)
}

推荐阅读