有没有办法创建每小时的RecurrenceRule?

时间:2015-07-09 00:01:44

标签: ios swift ekevent ekeventstore ekeventkit

我有一个EKEvent每4个小时发生一次,我想创建一个重复发生的事件。

不幸的是,EKRecurrenceRule课程中的可用频率是每日,每周,每月和每年。

如何设置EKRecurrenceRule对象的每小时频率?

1 个答案:

答案 0 :(得分:2)

不幸的是,没有办法使用EKRecurrenceRule对象制作每小时事件,但您仍然可以编写一个方法来执行相同操作。

    func createHourlyRecurringEvent(eventTitle: String, startDate: NSDate, endDate: NSDate, endReccurenceDate: NSDate, allDay : Bool, recurrenceSecondsInterval: Double, alarms: [EKAlarm]? , travelTime: Int?) {

    var eventStartDate = startDate
    var eventEndDate = endDate

    while eventStartDate.earlierDate(endReccurenceDate) != endReccurenceDate  {
        let event = EKEvent(eventStore: self.eventStore)

        event.title = eventTitle
        event.startDate = eventStartDate
        event.endDate = eventEndDate
        event.allDay = allDay
        event.alarms = alarms
        event.calendar = eventStore.defaultCalendarForNewEvents

        if let travelTime = travelTime {
            event.setValue(travelTime, forKey: "travelTime")
        }

        do {
            try eventStore.saveEvent(event, span: .ThisEvent)
            print("Hourly event created)")
            print("start date: \(formatter.stringFromDate(event.startDate)")
            print("End date: \(formatter.stringFromDate(event.endDate))")
        } catch {
            print("Event failed to save")
        }
        eventStartDate = NSDate(timeInterval: recurrenceSecondsInterval, sinceDate: event.startDate)
        eventEndDate = NSDate(timeInterval: recurrenceSecondsInterval, sinceDate: event.endDate)
    }
}

此代码位于我的Schedule类中。创建计划的实例后,我可以创建一个每小时重复的事件,如下所示:

 let startDate = NSDate()
 let endDate = NSDate(timeInterval: 10800, sinceDate: startDate)
 let oneWeekInSeconds = 604800.0
 let endRecurrenceDate = NSDate(timeInterval: oneWeekInSeconds, sinceDate: NSDate())
 let fourHours = 14400.0
 schedule!.createHourlyRecurringEvent("Testing",
                                         startDate: startDate,
                                         endDate: endDate,
                                         endReccurenceDate: endRecurrenceDate,
                                         allDay: false,
                                         recurrenceSecondsInterval: fourHours,
                                         alarms: nil,
                                         travelTime: nil)

删除单个事件非常简单,如下所示:

    func deleteEvent(eventToRemove: EKEvent) -> Bool {
    var successful = false
        do {
            print("deleting single event")
            try self.eventStore.removeEvent(eventToRemove, span: .ThisEvent)
            successful = true
        } catch {
            print("Bad things happened")
        }

    return successful
}

我还没有找到批量删除所有事件的好方法,因为它们都有不同的唯一ID。当我找到一个好方法时,我会更新这篇文章。