aroooo
aroooo

Reputation: 5056

Repeat Push Notification Every X Hours On The Hour

With UNCalendarNotificationTrigger I can get it to repeat at a specific hour every day.

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

With UNTimeIntervalNotificationTrigger I can get it to repeat by some interval from when the timer was created.

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: Double(frequency*60), repeats: true)

How though, can I get a push notification to repeat on the hour, at some flexible interval? For example, from 12:00am, every 2 hours, every 3 hours, or every 12 hours, and so on.

Upvotes: 0

Views: 699

Answers (1)

Cruceo
Cruceo

Reputation: 6824

Well, if you know you can set a specific time to repeat at each day, why not calculate the times based on the interval yourself?

var components = DateComponents()
components.hour = 5
components.second = 0

let interval: Double = 60 * 30 // 30 min
let maxDuration: Double = 60 * 60 * 5 // 5 hours
let startDate = Calendar.current.date(
    byAdding: components, 
    to: Calendar.current.startOfDay(for: Date()))
let endDate = startDate.addingTimeInterval(maxDuration)

let notificationCount: Int = Int((endDate.timeIntervalSince1970 - startDate.timeIntervalSince1970) / maxDuration)

(0..<notificationCount)
    .map({ startDate.addingTimeInterval(Double($0) * interval) })
    .forEach({ date in
        // Schedule notification for each date here
    })

You're going to have to manage the ranges and the day overlap yourself, but this should point you in the right direction.

Upvotes: 1

Related Questions