Swift: local notifications seem to be duplicated then some disappear

I have a reminders app that searches an array to send reminders to take medication. When the notifications show up, I get a sea of ​​multiple notifications that pop up and seem to disappear instantly and then 1 remains at the end.

My initial view controller is UITableViewController

. I tried to post the function fireNotifications

in viewDidLoad

but didn't seem to send any notifications. If I put a function call fireNotifications

in one of the tableView functions (i.e. numberOfSectionsInTableView

), I can get notifications, but they have the strange behavior that I mentioned above.

My code:

func fireNotifications() {
    if NSUserDefaults().boolForKey("NotifySwitch") {  //checks settings to make sure user wants reminders
        for (index, items) in myMedsList.enumerate() {
            let notification = UILocalNotification()
            notification.fireDate = NSDate(timeIntervalSinceNow: 20)
            notification.alertBody = "Reminder: Take your \(items.name) now!"
            notification.alertAction = "Let take my meds!"
            notification.soundName = UILocalNotificationDefaultSoundName
            notification.userInfo = ["Med Index": index]
            UIApplication.sharedApplication().scheduleLocalNotification(notification)
        }
    }
}

      

Am I wrong when I have a function call? Or is there something wrong in the code? Note that I just have firedate for as long as 20 seconds to test, but plan to set fireDate for each element in the myMedsList array.

+3


source to share


1 answer


It looks like you are adding all notifications every time. You should only add notifications that you have not previously added. If you don't like doing this, you can call cancelAllLocalNotifications()

before adding them back again.



+2


source







All Articles