Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why eventsMatchingPredicate returns nil?

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?

like image 541
OneZero Avatar asked Dec 25 '22 18:12

OneZero


1 Answers

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.

like image 144
Jamie A Avatar answered Jan 08 '23 06:01

Jamie A