Search code examples
iosswiftnotificationsuilocalnotification

Scheduling local notifications inside for-loop


I am having trouble scheduling local notifications inside a for-loop that schedules several notifications. For instance, the function takes in a variable called repetition which is an array of weekdays, with the purpose of scheduling a notification every weekday in the array. The problem is, notifications are fired when there is only one weekday and one scheduled notification. No notifications are fired when there is more than 1 item inside the array. Here is the complete function for clarity:

func scheduleNotification(at date: Date, every repetition: [String], withName name: String, id: String) {

    print("Scheduling notifications for the following days: \(repetition) \n \n")

    var components = DateComponents()
    let calendar = Calendar.current

    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)

    components.hour = hour
    components.minute = minutes

    for rep in repetition {
        switch rep {
            case "Sunday"   : components.weekday = 1
            case "Monday"   : components.weekday = 2
            case "Tuesday"  : components.weekday = 3
            case "Wednesday": components.weekday = 4
            case "Thursday" : components.weekday = 5
            case "Friday"   : components.weekday = 6
            case "Saturday" : components.weekday = 7

        default:
            break
        }

        let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)

        let content = UNMutableNotificationContent()
        content.title = name
        content.body = "Let's go!"
        content.sound = UNNotificationSound.default()

        let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)

        print("Added notification request for \(request.trigger?.description) \n")

        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print("Uh oh! We had an error: \(error)")
            }
        }
    }
}

Print log results

This fires a notification at the scheduled time:

Working

This does not fire a notification at the scheduled time:

Not working


Solution

  • Fixed it… I didn't realize notifications needed to have different identifiers. In the method above, I was using the same identifier for all scheduled notifications of the same kind. To fix it, I simply appended the weekday of each date to the notification identifier:

    let request = UNNotificationRequest(identifier: id + String(describing: components.weekday), content: content, trigger: trigger)
    

    Everything seems to be working in order now.