swift - 即使我使用 .randomElement() 方法 (Swift) 2019/2020,每日提醒(通知)也不会发送随机消息

标签 swift xcode

我制作了一个部分有效的每日提醒应用程序,因为它每天都会在我给出的指定时间发送每日提醒(通知)。但是,它不会随机化其发送的消息。尽管我按照以下行使用 .randomElements() 方法,但用户每天都会收到完全相同的消息: content.body = Remembers.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)

    }

最佳答案

每次收到相同文本的原因是随机元素函数仅在您设置正文时执行一次,而不是每次发送警报时执行。通知正文是由系统存储的字符串,系统无法存储指令从这三个字符串中选择一个随机字符串

如果您希望每天随机发出警报,则必须每天创建一个通知(可能最多一两周?),并将每个通知的正文设置为其中一个随机字符串。

关于swift - 即使我使用 .randomElement() 方法 (Swift) 2019/2020,每日提醒(通知)也不会发送随机消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59419029/

相关文章:

xcode - touchesbegan/moved/ended 不适用于 xcode 6.3

ios - 为什么已删除的文件在新写入文件后又会回来? swift 2.0

swift - 如何使用 SwiftUI 获取当前位置?

ios - Swift 函数的默认结果

ios - xcode Interface Builder 未更新 IBDesignable 类

xcode - 尝试编译 AFNetworking 2.0 时架构 i386 的 undefined symbol

swift - UItableViewCell 中的 Present 函数是否有替代方案?

ios - geocodeaddressString 提供了错误的坐标

iOS:以编程方式自动调整 UIImage 的大小

swift - 如何在swift中自动滚动消息