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)
}
}
Try this instead:
...
It looks like when we do:
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.