如何设置重复本地通知的开始和结束时间?

时间:2018-06-12 08:26:04

标签: ios swift uilocalnotification nsnotificationcenter

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

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

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

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

1 个答案:

答案 0 :(得分:0)

您可以从开始时间循环到结束时间安排单个通知,而不是使用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)