我尝试使用UNCalendarNotificationTrigger(dateMatching:, repeats:)重复通知,但是此方法只能在特定时间重复。

我还尝试了UNTimeIntervalNotificationTrigger(timeInterval:, repeats:)并按时间间隔重复了一次通知,但是此方法无法设置推送通知的开始时间。

而且这两种方法似乎没有地方设置结束推送通知的时间。

我想从一个特殊的时间开始,并定期重复通知。我该怎么办?

最佳答案

不用使用repeats参数,您可以从开始时间到结束时间调度各个通知。

let notifIDPrefix = "mynotif"
let notifCategory = "com.mydomain.mynotif" // this should have been registered with UNUserNotificationCenter

func scheduleNotifs(from startDate: Date, to endDate: Date, with interval: TimeInterval) {
    var curDate = startDate
    var count: Int = 0
    while curDate.compare(endDate) != .orderedDescending {
        scheduleNotif(with: "\(notifIDPrefix)_\(count)", date: curDate)
        curDate = curDate.addingTimeInterval(interval)
        count += 1
    }
}

private func scheduleNotif(with identifier: String, date: Date) {

    let content = UNMutableNotificationContent()
    content.title = "My Title"
    content.body = " "
    content.categoryIdentifier = notifCategory
    content.sound = UNNotificationSound.default()

    let triggerTime = Calendar.current.dateComponents([.year, .day, .hour, .minute, .second], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerTime, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request) { (error : Error?) in
        if let theError = error {
            print(theError.localizedDescription)
        }
    }
}

以下将安排3条通知(从现在开始的1分钟,2分钟和3分钟)。
    let startDate = Date().addingTimeInterval(60)
    let endDate = startDate.addingTimeInterval(60 * 2)
    let interval: TimeInterval = 60
    scheduleNotifs(from: startDate, to: endDate, with: interval)

关于ios - 如何设置重复本地通知的开始和结束时间?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50812544/

10-14 23:11
查看更多