UNUserNotificationCenter removeDeliveredNotificationRequests在使用UNCalendarNotificationTrigger

时间:2018-03-16 19:39:56

标签: ios swift unusernotificationcenter usernotifications unnotificationtrigger

我正在使用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中的一个错误。

编辑:{strong>不是this other SO question的重复,因为该问题根本没有讨论这个问题。可能会被视为this one的副本,但该答案没有任何答案。

0 个答案:

没有答案