如何在特定时间安排通知,然后每隔 x 时间重复一次?

How do I schedule a notification at a specific time, and then repeat it every x amount of time?

我正在制作一个提醒应用程序,您可以在其中安排提醒,然后每隔 x seconds/minutes/hours/days 等重复一次

如果我希望它每 x 次重复一次,我可以这样做:

func addNotification() {

let content = UNMutableNotificationContent()
content.title = "title"
// show this notification 5 minutes from now
var trigger: UNTimeIntervalNotificationTrigger
trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: true)
// choose a random identifier
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

// add our notification request
UNUserNotificationCenter.current().add(request)

}

这基本上就是我想要的,但不是从现在开始 5 分钟,我希望能够选择开始日期,然后从初始开始日期起每 5 分钟重复一次。

这可能吗?

据我所知,不可能在特定日期后每隔 X 秒(或其他时间)重复一次通知。

我认为这里的“最佳”选项是改用 UNCalendarNotificationTrigger 并从给定日期开始安排 60/5 = 12 次通知(因此每 5 秒 1 次)。

像这样:

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

现在基于此,当用户点击其中一个通知以取消所有其他通知时,您需要处理。但这是另一个话题,我留给你去寻找其中的逻辑。