swift - 即使我使用 .randomElement() 方法 (Swift) 2019/2020,每日提醒(通知)也不会发送随机消息
问题描述
我制作了一个部分有效的每日提醒应用程序,因为它每天在我给它的指定时间发送每日提醒(通知)。但是,它不会随机化它发送的消息。尽管我使用 .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
如果您希望警报每天都是随机的,您必须为每天创建一个通知(可能长达一两周?),并将每个通知的正文设置为随机字符串之一。
推荐阅读
- c# - 使用 BlobFromImage 时 EmguCV 访问冲突异常
- flutter - Flutter秒表后台运行
- php - 重定向 url 与 htaccess 完全匹配,如区分大小写
- python - 使用单个正则表达式在 python 中搜索 2 个条件
- reactjs - 我认为渲染工作两次
- javascript - Can I select all child elements of a specific element with a specific class without writing a list of selectors for each child?
- nginx - nginx proxy in front of Minio-like S3 server bad request
- javascript - How can I query select all inputs from table column
- excel - 使用 Chrome 和 VBA
- android - 当用户单击edittext之外的任何其他位置或屏幕上的任何其他位置时,如何隐藏edittext光标?