ios - 重复本地通知会删除先前待处理的本地通知
问题描述
我想每 30 分钟发送一次本地通知。我已经实现了重复本地通知,但它删除了前面的本地通知。场景如下所述:我的客户想要获得夜间警报。他希望早上醒来时可以立即查看所有通知警报。
这是代码:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound], completionHandler: {didAllow,error in })
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
let content = UNMutableNotificationContent()
content.title = "Hello"
content.subtitle = "I am your local notification"
content.body = "Yippppiiiieee...."
content.badge = 1
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: "testing", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
解决方案
先前的待处理通知被取消,因为您创建了一个具有相同identifier
. 根据文档
如果您提供唯一标识符,系统会创建一个新通知。
如果标识符与之前发送的通知匹配,系统会再次提醒用户,用新通知替换旧通知,并将新通知放在列表顶部。
如果标识符与待处理请求匹配,则新请求将替换待处理请求。
解决方案是始终UNNotificationRequest
使用新标识符创建
var notificationCount = 0
func applicationDidEnterBackground(_ application: UIApplication) {
// (...)
notificationCount += 1
let request = UNNotificationRequest(identifier: "testing\(notificationCount)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
推荐阅读
- spring - 无法从在 K8 中运行的 Spring Boot 应用程序连接到 Google Cloud MySQL DB
- c++ - 构造函数 - 复制常量引用 VS 移动复制值
- java - 我应该如何在 Java 中获得结果使用流?
- python - 如何安排脚本每天在 jupyter notebook 上运行?
- r - Shiny App中反应式条形图的问题
- compiler-errors - 编译错误:collect2.exe:错误:ld 返回 1 退出状态
- java - 有没有办法让微调器延迟显示其内容,直到发生某种情况?
- python - 在初始化之前获取类 __init__ 参数
- python-3.x - 无法在 VSCode 中使用 numpy 加载 txt 文件
- ajax - 使用codeigniter 3和ajax的带有时间范围的日期范围