ios - 如何在 Swift 5 中使用 UNTimeIntervalNotificationTrigger 停止 UNUserNotificationCenter?
问题描述
我有一个 UNUserNotificationCenter 每 60 秒发送一次本地通知。它的实现如下:
let userNotificationCenter = UNUserNotificationCenter.current()
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Test title"
notificationContent.body = "Test body"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60,
repeats: true)
let request = UNNotificationRequest(identifier: "testNotification",
content: notificationContent,
trigger: trigger)
userNotificationCenter.add(request) { (error) in
if let error = error {
print("Notification Error: ", error)
}
}
它运行良好,但我无法停止它,即使我的应用程序被杀死,它也会继续发送通知。
在这种情况下,阻止 UNUserNotificationCenter 发送通知的最佳方法是什么?
解决方案
您只需调用removePendingNotificationRequests(withIdentifiers:)
并传入您需要取消已安排但未发送的通知的标识符。
userNotificationCenter.removePendingNotificationRequests(withIdentifiers: ["testNotification"])
或者,如果您想删除应用程序的所有待处理通知,您可以调用removeAllPendingNotificationRequests()
。
推荐阅读
- mysql - Increment value is not coming order wise, when GROUP BY clause uses in select query in Mysql
- mysql - 如何关闭索引合并,MySQL
- .htaccess - Htaccess 不会将 jpg/png 图像重定向到脚本以在旅途中进行 webp 转换
- java - 在 tomcat 临时文件夹锁定的情况下配置 Glowroot 显示以下异常
- reactjs - JSX 循环不渲染
- javascript - (超链接审计)的特征检测
- javascript - 通过formarray进行Mat-select不显示选定的值和选项 - 反应形式Angular
- c# - 关于使用对象处理 ArrayList 的问题
- angular - Angular 7+ 在 ngModel 上使用 CustomPipe
- python - 为 dask 数据框列创建 dask 列表