Search code examples
iosxcodeekeventstore

iOS: predicateForEventsWithStartDate does not return events starting outside of search frame


Simple example I use with the code in the snippet below:

Search frame: 15 Apr 2016 15:00pm-18:00pm

Events which are entered in the calendar:

  • Event 1: 15 Apr 2016 12:00pm-16:00pm
  • Event 2: 15 Apr 2016 17:00pm-20:00pm

Now the used method returns me only one object - that is the Event 2. Apparently I hope to get returned both - Event 1 and 2.

I really don't understand why this happens! What do I miss in my code? Thanks in advance.

int seconds_in_year = 60*60*24*365;
__block
NSDate* currentStart = [NSDate dateWithTimeInterval:0 sinceDate:startTime];
__block
NSDate* currentFinish = [NSDate dateWithTimeInterval:seconds_in_year sinceDate:currentStart];
// use Dictionary for remove duplicates produced by events covered more one year segment
NSMutableDictionary *eventsDict = [NSMutableDictionary dictionaryWithCapacity:1024];

EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
    if (!granted) { return; }

    // enumerate events by one year segment because iOS do not support predicate longer than 4 year !
    while ([currentStart compare:endTime] == NSOrderedAscending) {
        if ([currentFinish compare:endTime] == NSOrderedDescending) {
            currentFinish = [NSDate dateWithTimeInterval:0 sinceDate:endTime];
        }
        NSPredicate *predicate = [store predicateForEventsWithStartDate:currentStart endDate:currentFinish calendars:nil];

        [store enumerateEventsMatchingPredicate:predicate
                                     usingBlock:^(EKEvent *event, BOOL *stop) {

                                         if (event) {
                                             [eventsDict setObject:event forKey:event.eventIdentifier];
                                         }
                                     }];
        currentStart = [NSDate dateWithTimeInterval:(seconds_in_year + 1) sinceDate:currentStart];
    }
    return;
}];

EDIT:

If I try another Event 3 (15 Apr 2016 14:00pm-19:00pm) then the method returns me the whole search period as to be an "event" in the calendar. That is correct compared to the previous situation which still causes me some headaches.


Solution

  • As the method name implies predicateForEventsWithStartDate searches for startDates which are equal to or later than the passed date argument.