I want to send the user TimeInterval Notifications, but it should send in every Notification an other element from my array (other message) But only in the first message its a randomElement and then in the others there are all the same as the first. But I want every time an other message in the Notification.
class ViewController: UIViewController {
let unCenter = UNUserNotificationCenter.current()
var myFirstArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
override func viewDidLoad() {
super.viewDidLoad()
unCenter.requestAuthorization(options: [.alert, .sound, .badge]) { (didAllow, error) in
print(error ?? "No error")
}
unCenter.delegate = self
}
@IBAction func button_Tapped(_ sender: UIButton) {
if let random = myFirstArray.randomElement(){
sendNotification(body: random, time: 70)
}
}
func sendNotification(body: String, time: TimeInterval){
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)
}
}
extension ViewController: UNUserNotificationCenterDelegate{
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
print("will present")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("did receive")
}
}
If you need a random element each time you must register for different notifications at a time interval that keeps on increasing as you register each notification. Also, make sure you're setting the
repeatsparameter set as false. Here, you're just making a single notification and set it as repeating which means you get the same notification at the specified time interval. Here's a code snippet of how you can achieve this.