how do i schedule a notification at a specific time and then repeat it every time i do?

From what I know it’s not possible to repeat a notification every X seconds (or something else) after a specific date.

I think the “best” option here is to use UNCalendarNotificationTrigger instead and schedule 60/5 = 12 notification (so 1 every 5 seconds) starting from the given date.

Something like this:

// this is your reference date - here it's now + 5 seconds just for this example
var referenceDate = Calendar.current.date(byAdding: .second, value: 5, to: Date())!
for i in 0...11 { // one every 5 seconds, so total = 12
    let content = UNMutableNotificationContent()
    content.title = "Notif \(i)"
    content.body = "Body"

    var dateComponents = DateComponents(calendar: Calendar.current)
    // 5 seconds interval here but you can set whatever you want, for hours, minutes, etc.
    dateComponents.second = 5
    //dateComponents.hour = X
    // [...]
    
    guard let nextTriggerDate = dateComponents.calendar?.date(byAdding: dateComponents, to: referenceDate),
          let nextTriggerDateCompnents = dateComponents.calendar?.dateComponents([.second], from: nextTriggerDate) else {
        return
    }
    referenceDate = nextTriggerDate

    print(nextTriggerDate)
    let trigger = UNCalendarNotificationTrigger(dateMatching: nextTriggerDateCompnents, repeats: true)
    let request = UNNotificationRequest(identifier: "notif-\(i)", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request)
}

Now based on that, you would need to handle when a user taps one of the notifications in order to cancel all the others. But that’s another topic here and I leave it up to you to find the logic for that.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top