1

我正在制作一个提醒应用程序,您可以在其中安排提醒,然后每隔 x 秒/分钟/小时/天等重复一次。

如果我希望它每 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 分钟重复一次。

这可能吗?

4

1 回答 1

0

据我所知,不可能在特定日期后每隔 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)
}

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

于 2020-10-28T17:03:18.290 回答