在 for 循环中安排本地通知

Scheduling local notifications inside for-loop

我在安排多个通知的 for 循环内安排本地通知时遇到问题。例如,该函数接受一个名为 repetition 的变量,它是一个工作日数组,目的是在数组中的每个工作日安排一个通知。问题是,当只有一个工作日和一个预定通知时,就会触发通知。当数组中有超过 1 个项目时,不会触发任何通知。为清楚起见,这里是完整的函数:

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

打印日志结果

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

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

已修复…我没有意识到通知需要有不同的标识符。在上面的方法中,我对所有同类的预定通知使用相同的标识符。要修复它,我只是将每个日期的工作日附加到通知标识符:

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

现在似乎一切正常。