我做了一个部分工作的每日提醒应用程序,因为它每天在我给它的指定时间发送每日提醒(通知(。但是,它不会随机化它发送的消息。用户每天都会收到完全相同的消息,尽管我按照以下行使用 .randomElements(( 方法:content.body = reminders.randomElement((!
有什么原因导致消息不随机化/我如何解决它?
提前谢谢你。
var reminders = ["message 1", "message 2", "message 3"]
@IBAction func setReminder(_ sender: Any) {
label.text = "Reminders: Set. Daily 4:00 p.m."
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Facts, tips, and tricks to help you quit:"
content.body = reminders.randomElement()!
reminders.shuffle()
content.sound = .default
content.userInfo = ["value": "Data with local notification"]
let date = Date()
let calendar = Calendar.current
//let hour = calendar.component(.hour, from: date)
//let minute = calendar.component(.minute, from: date)
//let second = calendar.component(.second, from: date)
var dateComponents = DateComponents()
dateComponents.hour = 16
dateComponents.minute = 0
dateComponents.second = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(i) * 5, repeats: false)
let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
center.add(request)
}
每次都收到相同文本的原因是,随机元素函数仅在设置正文时执行一次,而不是每次发送警报时都执行。通知正文是系统存储的String
,系统无法存储指令select a random string from these three
如果您希望警报每天都是随机的,则必须每天创建一个通知(可能长达一两周?(,并将每个通知的正文设置为随机字符串之一。