I'm working on app where user can set time for everyday local notification, then I have an option to enable or disable these notifications. My question how I can disable/cancel already setted notification?
Here in one of this IFs I need to cancel notif
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (indexPath as NSIndexPath).row == 1 && switchiBtn.isOn == false {
return 0.0
}
if (indexPath as NSIndexPath).row == 2 {
if switchiBtn.isOn == false || dpVisible == true {
return 0.0
}
return 216.0
}
if (indexPath as NSIndexPath).row == 3 {
if switchiBtn.isOn == false || dpVisible == true {
return 0.0
}
return 44
}
return 50.0
}
Here are functions for schedule and button where I'm setting notif.
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)
}
})
}
@IBAction func setACTION(_ sender: AnyObject) {
let hour = datePicker.calendar.component(.hour, from: datePicker.date)
let minute = datePicker.calendar.component(.minute, from: datePicker.date)
var dateComponents = DateComponents()
dateComponents.hour = hour
dateComponents.minute = minute
print(dateComponents)
scheduleNotif(date: dateComponents, completion: { success in
if success {
print("SUCCESS")
} else {
print("ERROR")
}
})
Thanks.
As mentioned here you can cancel all notifications with the following code:
UIApplication.sharedApplication().cancelAllLocalNotifications()
The way same
UNNotification
is identify are base on theidentifier
passed when you create theUNNotificationRequest
.In your example above,
You have actually hardcoded the
identifier
to be"myNotif"
. This way, whenever you want to delete the already set notification you can do this:However, do take note that when you hardcode the identifier, every time when you add a
request
toUNUserNotificationCenter
the notification is actually being replaced.Example, if you scheduled a
"myNotif"
request
set on 1 minute later but you call another function to schedule a"myNotif"
at 1 hour later it will be replaced. Therefore only the latest"myNotif"
at one hour later will be in thependingNotificationRequest
.For cancelling all pending notifications, you can use this:
For cancelling specific notifications,