Search code examples
iosswifteventkitekeventstore

How to retrieve events older than 3 years old from EKEventStore


I just ran the following code (on my iPhone):

  let predicate = eventStore.predicateForEvents(withStart: Date(timeIntervalSinceNow: -60*60*24*365*4), end: Date(timeIntervalSinceNow: 60*60*24*30), calendars: [calendar])

The results show that this request only goes back 3 years:

earliest start date found: 2015-04-11 12:00:00 +0000

Is there a way to retrieve calendar events older than three years? I'd like to retrieve my old class notes. When I use the calendar on the mac, it lists counts for each calendar, yet I'm unable to retrieve the older objects.


Solution

  • ** Updated answer **

    I dug into this a bit more and found the following from Apple which explains why the OP Is having this problem:

    For performance reasons, this method matches only those events within a four year time span. If the date range between startDate and endDate is greater than four years, it is shortened to the first four years.

    With that said, you can just create four year increments with the following code as an example:

    if let fourYearsAgo = Calendar.current.date(byAdding: .year, value: -4, to: Date()) {
        let predicate = eventStore.predicateForEvents(withStart: fourYearsAgo,
                                                      end: Date(),
                                                      calendars: [calendar])
    }