Search code examples
iosxcodeios5calendarios6

How to get all events from an EKCalendar in iOS


I've created a calendar with some events, now I want to get all events from that calendar, without knowing what their start or end date is.

Code I tried, getting all events from all calendars, so I could divide them by calendar ID later or so.. :

NSPredicate *fetchCalendarEvents = [eventStore predicateForEventsWithStartDate:[NSDate distantPast] endDate:[NSDate distantFuture] calendars:eventStore.calendars];

NSArray *allEvents = [eventStore eventsMatchingPredicate:fetchCalendarEvents];

This makes allEvents return nil while the database clearly shows events in the calendar.

Anyone could help me?


Solution

  • I have it working now.

    This is the code I'm using:

    NSDate* endDate =  [NSDate dateWithTimeIntervalSinceNow:[[NSDate distantFuture] timeIntervalSinceReferenceDate]];
    NSArray *calendarArray = [NSArray arrayWithObject:cal];
    NSPredicate *fetchCalendarEvents = [eventStore predicateForEventsWithStartDate:[NSDate date] endDate:endDate calendars:calendarArray];
    NSArray *eventList = [eventStore eventsMatchingPredicate:fetchCalendarEvents];
    
    for(int i=0; i < eventList.count; i++){
    
        NSLog(@"Event Title:%@", [[eventList objectAtIndex:i] title]);
    
    }
    

    Gives me all events from the calendar I'm using for my app from the date it is right when you call the method.

    I think giving [NSDate distantPast] won't work because it's in the past or something.. setting your startDate as [NSDate date] will work.

    Hope this helps people who have the same problem..