gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:21:27 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com