Prelude
I have mentioned the fact that I am working on my first iOS app in a number of my previous posts and as such I face a number of newbie/noob(?) problems. In this post, I will talk about one such problem, the problem of why I cannot cancel local notifications in iOS app. They are not really problems as much as they are simply things that I do not know, for e.g. the following,
- how do I get the day of the week?
- where is my string.replaceAll in Swift?
- knowing which local notification brought my app to foreground?
- serving HTML content in an iOS app that works on iOS 7 and above
So this post basically describes another very simple problem that I have found a solution to, but I do not fully understand why the problem was occurring in the first place.
Introduction
As I have mentioned in this post, my iOS app uses local notifications i.e. UILocalNotification and in my app a certain chain of events can cause the local notifications to be cancelled. Sounds fairly straight forward right? Well it is and it is not, read on to find out exactly what I mean
My problem
- cancelAllLocalNotifications: Cancels the delivery of all scheduled local notifications.
- cancelLocalNotification: Cancels the delivery of the specified scheduled local notification.
Cannot cancel local notifications in iOS app
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification)
As I have identified before, there are 2 methods to cancel local notifications, now if I just used the cancelAllNotifications method, in the AppDelegate as follows,
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
application.cancelAllLocalNotifications()
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
let dict = notification.userInfo!
let notificationType = dict["type"] as! Int
let notificationTypeX = 99
if notificationType == notificationTypeX {
//cancel all notifications of type X
for notification:AnyObject in UIApplication.sharedApplication().scheduledLocalNotifications {
let localNotification = notification as! UILocalNotification
let lnDict = notification.userInfo!
let type = lnDict["type"] as! Int
if type == notificationType {
application.cancelLocalNotification(localNotification)
}
}
}
}
How did I solve my problem?
func cancelNotification(category:Int) {
let application = UIApplication.sharedApplication()
for notification:AnyObject in application.scheduledLocalNotifications {
let scheduledNoti = notification as! UILocalNotification
if let type = scheduledNoti.userInfo?["type"] as? Int {
if type == category {
application.cancelLocalNotification(scheduledNoti)
}
}
}
}
As usual, if you find any of my posts useful support me by buying or even trying one of my apps on the App Store.
Also, if you can leave a review on the App Store or Google Play Store, that would help too.
0 Comments