How do I retrieve an EKEvent that is greater than 1 month old?

416 views Asked by At

using this code:

    func sampleCase() {
    var dateConstructor = DateComponents()
    dateConstructor.year = 2016
    dateConstructor.month = 12
    dateConstructor.day = 15
    let calendar: Calendar = Calendar.current
    let workCalendar = CalendarUtilities.calendar("WorkSchedule", using: eventStore)
    let referenceDate = calendar.date(from: dateConstructor)!
        let startDate = referenceDate
        let endDate = referenceDate.addingDays(1)  // midnight
        let range = DateRange(start: startDate, andEnd: endDate)
    let predicate = eventStore.predicateForEvents(withStart: range.startDate, end:range.endDate, calendars:[workCalendar])
    let events = eventStore.events(matching: predicate)
    print("Found: \(events.count) events")
    print("used:\(startDate)")
    print("\(endDate)")

}

I only get correct results for events in the previous month... (These examples use dates that have events and should return non-zero values.)

authorization was granted...
Found: 1 events
used:2016-12-15 05:00:00 +0000
2016-12-16 05:00:00 +0000

going back earlier results in 0 events. I also tried using enumeration with similar results:

        eventStore.enumerateEvents(matching: predicate) { (result, stop) in
        counter += 1
    }
    print("found \(counter) items using iterator")

used:2016-11-11 05:00:00 +0000
2016-11-12 05:00:00 +0000
found 0 items using iterator

Is it possible to retrieve events from, say 2014? I see them when using the calendar app (macOS and iOS).

2

There are 2 answers

0
Mozahler On BEST ANSWER

I think what happened is that the settings on my device changed during the iOS upgrade process (I know not how). In Settings/Calendar You can specify how events are synched. I found it was set to "1 month". I am now able to retrieve events older than 1 month.

3
ghostatron On

The event store should return whatever matches the predicate you give it as long as you don't make the range too large (there IS a limit, I'd have to go look it up). In your example, you're only telling it to search within a range of 1 day. You're also narrowing it down to one specific calendar (you can pass nil to search all calendars). If you want events from 2014, then give it a range in 2014.