如何禁用/取消已设置的通知?
这是我的调度函数。
func scheduleNotif(date: DateComponents, completion: @escaping (_ Success: Bool) -> ()) {
let notif = UNMutableNotificationContent()
notif.title = "Your quote for today is ready."
notif.body = "Click here to open an app."
let dateTrigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: dateTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if error != nil {
print(error)
completion(false)
} else {
completion(true)
}
})
}发布于 2016-11-12 22:00:00
要取消所有挂起的通知,您可以使用以下命令:
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()为了取消特定的通知,
UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
var identifiers: [String] = []
for notification:UNNotificationRequest in notificationRequests {
if notification.identifier == "identifierCancel" {
identifiers.append(notification.identifier)
}
}
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
}发布于 2016-11-12 22:05:23
识别相同 UNNotification的方式是基于创建identifier时传递的UNNotificationRequest。
在上面的示例中,
let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: dateTrigger)实际上,您已经将identifier硬编码为"myNotif"。这样,当您想要删除已设置的通知时,您可以这样做:
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: "myNotif")但是,请注意,当您对标识符进行硬编码时,每次向UNUserNotificationCenter添加request时,通知实际上都会被替换。
例如,如果您在1分钟后安排了一个"myNotif" request设置,但您调用另一个函数在1小时后安排了一个"myNotif",则它将被替换。因此,只有一小时后的最新"myNotif"将在pendingNotificationRequest中。
发布于 2016-11-12 21:46:48
正如前面提到的here,您可以使用以下代码取消所有通知:
UIApplication.sharedApplication().cancelAllLocalNotifications()
https://stackoverflow.com/questions/40562912
复制相似问题