rod*_*sal 2 notifications ios uilocalnotification swift
我在安排多个通知的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)")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
打印日志结果
这会在预定时间触发通知:
这不会在计划的时间触发通知:
修复它…我没有意识到通知必须具有不同的标识符。在上述方法中,我对相同种类的所有计划通知使用相同的标识符。要解决此问题,我只需将每个日期的工作日附加到通知标识符:
let request = UNNotificationRequest(identifier: id + String(describing: components.weekday), content: content, trigger: trigger)
Run Code Online (Sandbox Code Playgroud)
现在一切似乎都正常了。
| 归档时间: |
|
| 查看次数: |
627 次 |
| 最近记录: |