ios - 在 for 循环中安排本地通知

标签 ios swift notifications uilocalnotification

我在安排多个通知的 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)")
            }
        }
    }
}

打印日志结果

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

Working

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

Not working

最佳答案

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

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

现在一切似乎都在按顺序进行。

关于ios - 在 for 循环中安排本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41493722/

相关文章:

ios - 如何打开 .swiftmodule 文件

ios - 设置重复本地通知的日期

mysql - 如何实现通知制度?

ios - 单例 Swift 共享 [字符串]

ios - 长时间运行的异步任务 - 如何在用户可能导航到的任何 View Controller 中接收回调

loops - Swift 遍历字典数组

ios - 计算器中的函数等于

iOS swift : How to post a video to twitter with TwitterKit?

Cocoa:对使用 CoreData 和 Bindings 与 UI 对象交互感到困惑

ios - 如何在 RPGLE 中构建 APNS 通知?