首页 > 解决方案 > 即使我使用 .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)

    }

标签: swiftxcode

解决方案


每次都得到相同文本的原因是随机元素函数只执行一次,当您设置正文时,而不是每次发送警报时。通知的正文是String系统存储的,系统不能存储指令select a random string from these three

如果您希望警报每天都是随机的,您必须为每天创建一个通知(可能长达一两周?),并将每个通知的正文设置为随机字符串之一。


推荐阅读