ios - 如果应用程序已关闭或在后台,如何删除特定的远程通知
问题描述
我的应用程序有一个聊天服务,当收到新的通知时,我想清除 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])
}
}
}
其中类型是自定义值。当应用程序在后台或被用户关闭时如何执行此操作。
解决方案
您需要打开后台模式功能并检查远程通知模式。为了在后台删除通知,您需要发送一个没有警报的新通知,例如{"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)
}
推荐阅读
- vue.js - Why does the vue effect not run through the scheduler when the effect is initialized?
- javascript - 为什么即使我在初始化云函数目录时选择了 TypeScript,Firebase CLI 也会问我是否想使用 ESLint?
- java - How to make a grid shape using Linearlayout?
- javascript - Javascript Split innerText and wrap with a Span
- python-3.x - discord.py - 如何将命令添加到父命令
- swiftui - SwiftUI 导航视图 - 在多个视图中处理大小类
- javascript - 为什么 .append() 会替换下面代码中 tbody 的内容?
- css - CSS:即使在滚动后也带有圆角的正文边框
- html - 部署后 11 IE 中的标题和导航标签无法正常工作
- json - 在 TypeScript 中更改导入 JSON 的类型