LearningSwift
LearningSwift

Reputation: 143

Swift: Local notifications seem to duplicate then some vanish

I have a reminder app that is searching through an array to send reminders to take a medication. When the notifications come through, I'm getting a sea of multiple notifications coming through and seemingly vanishing instantaneously and then 1 remains at the end.

My initial view controller is a UITableViewController. I tried placing my fireNotifications function in viewDidLoad but it didn't seem to send any notifications. If I put the fireNotifications function call in one of the tableView functions (ie numberOfSectionsInTableView) I'm able to get the notifications to come through, but they have the odd behavior I mentioned above.

My code is:

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's take my meds!"
            notification.soundName = UILocalNotificationDefaultSoundName
            notification.userInfo = ["Med Index": index]
            UIApplication.sharedApplication().scheduleLocalNotification(notification)
        }
    }
}

Am I making a mistake in where I have the function call? Or is there something wrong in the code? Of note, I just have the fireDate as 20 seconds for testing purposes, but plan on customizing the fireDate for each item in the myMedsList array.

Upvotes: 3

Views: 888

Answers (1)

Aaron Brager
Aaron Brager

Reputation: 66242

It looks like you're adding all notifications every time. You should only add the notifications you haven't added before. If you don't feel like doing that, you can call cancelAllLocalNotifications() before adding them all back in again.

Upvotes: 2

Related Questions