Random Element from Array with repeating TimeIntervalNotificationTrigger

201 Views Asked by At

when I click on the Button, it should send every 90 seconds a randomElement from my array. But it sends always the same. For example, the first Notifications is an "A", all other Notifications are also an A. But I want that they are random from the array and I also would like, that I can save the actually randomElement in an other var.

class ViewController: UIViewController {

    var meinArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "A", "B", "C", "D"]

    override func viewDidLoad() {
        super.viewDidLoad()

        authorize()
    }


    @IBAction func button_Tapped(_ sender: UIButton) {

        if let random = meinArray.randomElement(){
            addNotification(time: 90, body: random)
        }
    }


    let uncenter = UNUserNotificationCenter.current()

    func authorize(){

        uncenter.requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
            print(error ?? "No error")
        }
        configure()
    }

    func configure(){

        uncenter.delegate = self
    }

    func addNotification(time: TimeInterval, body: String){

        let content = UNMutableNotificationContent()
        content.body = body
        content.sound = .default

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: time, repeats: true)

        let request = UNNotificationRequest(identifier: "request", content: content, trigger: trigger)

        uncenter.add(request, withCompletionHandler: nil)
    }

}
1

There are 1 best solutions below

1
paulRick On

Try this instead:

@IBAction func button_Tapped(_ sender: UIButton) {
    Timer.scheduledTimer(timeInterval: 90, target: self, selector: #selector(showArray), userInfo: nil, repeats: true)
}

@objc func showArray() {
    if let random = meinArray.randomElement() {
        let content = UNMutableNotificationContent()
        content.body = random
        content.sound = .default

        let request = UNNotificationRequest(identifier: "request", content: content, trigger: nil)

        uncenter.add(request, withCompletionHandler: nil)
    }
}

...

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler( [.alert, .badge, .sound])
}

It looks like when we do:

if let random = meinArray.randomElement(){
    addNotification(time: 90, body: random)
}

And then add to the NotificationCenter, the callback will not run .randomElement() again, instead it will just take the element of the first and only call to it.