I am scheduling a location based UILocalNotification
with the click of a button . But when i try to cancel the localNotification by clicking the same button again, it doesn't cancel the notification.
I am using UIApplication.sharedApplication().cancelLocalNotification(localNotification)
to cancel my scheduled location based local notification.
What am i doing wrong ?
here is my implementation
@IBAction func setNotification(sender: UIButton!) {
if sender.tag == 999 {
sender.setImage(UIImage(named: "NotificationFilled")!, forState: .Normal)
sender.tag = 0
regionMonitor() //function where notification get scheduled
} else {
sender.setImage(UIImage(named: "Notification")!, forState: .Normal)
sender.tag = 999 }
what should i enter into the else block so that the scheduled notification gets canceled. Cannot clear all notifications.
here is the didEnterRegion
block code where i trigger the local notification
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
localNotification.regionTriggersOnce = true
localNotification.alertBody = "Stack Overflow is great"
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
NSLog("Entering region")
}
You could try to remove all notifications if this is acceptable in your context. Like this:
for notification in UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] {
UIApplication.sharedApplication().cancelLocalNotification(notification)
}
Or as stated by Logan:
UIApplication.sharedApplication().cancelAllLocalNotifications()
Or as stated by Gerard Grundy for Swift 4:
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
You can cancel a notification using its identifier :
let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: [String])
center.removePendingNotificationRequests(withIdentifiers: [String])
Solution for iOS 10+ Swift 3.1
let center = UNUserNotificationCenter.current()
center.removeAllDeliveredNotifications() // To remove all delivered notifications
center.removeAllPendingNotificationRequests()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With