3

我正在使用 iOS 10 中引入的较新的通知 API,并在 Swift 中工作。当我创建本地通知时,它会正确显示,但是当发生相关操作时,我会尝试在我的应用中将其删除(这样用户就不必手动清除它)。但是传递的通知似乎仍然存在。

我正在安排这样的本地通知:

let fireDate = Date() // some date, inputted as a method parameter
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.day, .month, .year, .hour, .minute], from: fireDate)

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

let notificationContent = UNMutableNotificationContent()
notificationContent.title = "some title"
notificationContent.body = " some message"
notificationContent.userInfo["custom key"] = "my custom key"
notificationContent.badge = 1

var components = DateComponents()
components.day = 10
notificationContent.userInfo["endDate"] = calendar.date(byAdding: components, to: fireDate) // haven't verified if this even works, but saw this as a way to set notifications to expire automatically, including for completeness

let request = UNNotificationRequest(identifier: identifier, content: notificationContent, trigger: trigger)

UNUserNotificationCenter.current().add(request) { (error) in
    if let error = error {
        print(error)
    }
}

当我的应用程序中发生的操作导致通知不再相关时,我想将其从通知中心中删除,或者如果尚未触发,则阻止它触发:

func clearNotification(withIdentifier: String) {
    let identifiers = [identifier]
    UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
    UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: identifiers)
    UIApplication.shared.applicationIconBadgeNumber = UIApplication.shared.applicationIconBadgeNumber - 1
}

我已检查以确保标识符正确匹配。如果通知尚未触发,则不会。但是如果通知已经触发,它似乎会无限期地留在通知中心。应用程序徽章图标似乎确实按预期工作,但removeDeliveredNotifications如果不是从通知中心删除通知,我真的不明白它的用途。

注意:我已经在模拟器以及实际的 iPhone (iOS 11.2.6) 上对其进行了测试。

它似乎与特别相关,UNCalendarNotificationTrigger因为如果我切换到使用UNTimeIntervalNotificationTrigger一切似乎都可以正常工作。当我打电话时,基于时间间隔触发器的通知会消失,removeAllDeliveredNotifications并显示在getDeliveredNotifications. 我不明白为什么UNCalendarNotificationTrigger会有不同的行为(我在文档中读到基于位置的触发器有点不同,但不是日历触发器)。我怀疑这是iOS中的一个错误。

编辑:不是这个其他 SO 问题的重复,因为那个问题根本没有讨论这个问题。可能被认为是这个的副本,但那个没有任何答案。

4

0 回答 0