每小时一次X小时重复推送通知

时间:2017-10-23 07:29:05

标签: ios swift apple-push-notifications

使用UNCalendarNotificationTrigger我可以让它在每天的特定时间重复。

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

使用UNTimeIntervalNotificationTrigger我可以在创建计时器之后的某个时间间隔重复它。

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

尽管如此,我可以在一个灵活的时间间隔内获得按小时重复的推送通知吗?例如,从凌晨12:00开始,每隔2小时,每隔3小时或每隔12小时,依此类推。

1 个答案:

答案 0 :(得分:1)

嗯,如果你知道你可以设定每天重复的具体时间,为什么不自己根据时间间隔计算时间?

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
    })

你将不得不自己管理范围和日重叠,但这应该指向正确的方向。