Question

Here's my code:

NSString * calID = [[NSUserDefaults standardUserDefaults] objectForKey:@"calendarIdentifier"];
EKCalendar *cal = [eventStore calendarWithIdentifier:calID];

// If calendar exists
if(cal)
{
    // Retrieve all existing events until today
    NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:[NSDate distantPast] endDate:[NSDate date] calendars:@[cal]];
    self.events = [eventStore eventsMatchingPredicate:predicate];

    if(self.events==nil)
        NSLog(@"nil events!");
 }

The calendarItentifier is the variable that I stored when I created the calendar in my program, so it's not the case I'm adding events on the wrong calendar.

However, the code does not work to retrieve past events on the calendar, it simply returns nil to self.events. But I DID add events on the calendar. Can anything tell me if there's anything wrong with the code?

Was it helpful?

Solution

According to this answer and this post, EKEventStore eventsMatchingPredicate: doesn't support predicates with a startDate and endDate more than four years apart. I can't find any official documentation on this fact, but in practice the method appears to just return events up to endDate or four years after startDate, whichever comes first.

[NSDate distantPast] returns a date centuries in the past, so you're all but guaranteed to get a wrong answer if you create a predicate with that as your start date.

The simplest solution would be to change your code to something like this:

NSDate* fourYearsAgo = [NSDate dateWithTimeIntervalSinceNow:-1 * 60 * 60 * 24 * 365 * 4];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fourYearsAgo endDate:[NSDate date] calendars:@[cal]];

If this doesn't work for you, you'll either have to find a way to choose your bounds more wisely or create successive four-year predicates until you find what you're looking for.

OTHER TIPS

The most likely cause is that eventStore is nil. Any time you encounter a "nothing seems to happen" bug, you should first look to see if anything is nil.

For me this occurred because the startDate and endDate were the same. To remedy this, I increased the endDate in the query by one second and it now returns the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top