重复本地通知删除之前未决的本地通知

Repeating local notification removes previous pending local notifications

我想每 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 的新通知。根据 documentation

If you provide a unique identifier, the system creates a new notification.

If the identifier matches a previously delivered notification, the system alerts the user again, replaces the old notification with the new one, and places the new notification at the top of the list.

If the identifier matches a pending request, the new request replaces the pending request.

解决方案是始终使用新标识符

创建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)
}

首先你不应该使用相同的标识符,因为它会删除已经安排好的标识符

 let request = UNNotificationRequest(identifier: "testing", content: content, trigger: trigger)

秒你必须插入不同的 TimeInterval

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)

//

(1...10).forEach {

    let content = UNMutableNotificationContent()
    content.title = "Hello \([=12=])"
    content.subtitle = "I am your local notification \([=12=])"
    content.body = "Yippppiiiieee.... \([=12=])"
    content.badge = 1
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval:TimeInterval([=12=]*1800), repeats: false)
    let request = UNNotificationRequest(identifier: "testing\([=12=])", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}

不要使用相同的标识符。它将覆盖之前的通知。

现在你会问,如果我每次都生成一个随机字符串,我将如何识别点击了哪个通知?

假设您有这个名为 "coffeeTimeNotificationID" 的标识符。只需将时间戳值 ([NSDate timeIntervalSinceReferenceDate]]) 附加到此字符串即可。现在你的字符串看起来像这样:“coffeeTimeNotificationID1232134314”。

每当用户点击此通知时,只需在标识符字符串中搜索“coffeeTimeNotificationID”。如果找到它,您就会知道窃听了哪种类型的通知。