首页 > 解决方案 > 重复本地通知会删除先前待处理的本地通知

问题描述

我想每 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)

}

标签: iosswiftlocalnotificationunnotificationrequestunnotificationtrigger

解决方案


先前的待处理通知被取消,因为您创建了一个具有相同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)
}

推荐阅读