在for循环中调度本地通知

时间:2017-01-05 20:04:13

标签: ios swift notifications uilocalnotification

我无法在调度多个通知的for循环中调度本地通知。例如,该函数接受一个名为repetition的变量,该变量是工作日的数组,其目的是在数组中的每个工作日安排通知。问题是,当只有一个工作日和一个预定通知时会触发通知。当数组中有多个项目时,不会触发通知。以下是完整的功能:

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)")
            }
        }
    }
}

打印日志结果

这会在预定时间触发通知:

Working

这不会在预定时间触发通知:

Not working

1 个答案:

答案 0 :(得分:6)

修正了......我没有意识到需要具有不同标识符的通知。在上面的方法中,我对同一类型的所有预定通知使用相同的标识符。为了解决这个问题,我只需将每个日期的工作日添加到通知标识符中:

{{1}}

现在一切似乎都在按顺序运作。