I'm having trouble checking if an event exists in the user's calendar. I need to check this to determine whether I add it or not so that I do not duplicate calendar entries. Right now, I am duplicating the entry every time I run the code.
First, this is how I create a calendar entry:
+ (NSString *) addEventToCalenderWithDate : (NSDate *) eventDate eventTitle : (NSString *) eventTitle eventLocation : (NSString *) eventLocation allDayEvent : (BOOL) isAllDay { EKEventStore *store = [[EKEventStore alloc] init]; [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { if (!granted) { returnValue = @"calendar error"; } else if ([self eventExists:dateAndTime eventTitle:eventTitle allDayEvent:isAllDay]) { returnValue = @"duplicate"; } else { EKEvent *event = [EKEvent eventWithEventStore:store]; event.title = eventTitle; event.startDate = dateAndTime; if (eventTimeString == (id)[NSNull null] || eventTimeString.length == 0 || isAllDay) { event.allDay = YES; event.endDate = dateAndTime; } else { event.endDate = [event.startDate dateByAddingTimeInterval:60*60];
This sets the event correctly. However, if I run it again, I expect the else if clause to return YES and a new record will not be created. However, it always returns NO , and I create a new calendar entry every time I execute. Here is the method:
+ (BOOL) eventExists : (NSDate *) date eventTitle : (NSString *) eventTitle allDayEvent : (BOOL) isAllDay { EKEventStore *store = [[EKEventStore alloc] init]; NSPredicate *predicateForEventOnDate = [[NSPredicate alloc] init]; if (isAllDay) predicateForEventOnDate = [store predicateForEventsWithStartDate:date endDate:date calendars:nil]; // nil will search through all calendars else predicateForEventOnDate = [store predicateForEventsWithStartDate:date endDate:[date dateByAddingTimeInterval:60*60] calendars:nil]; // nil will search through all calendars NSArray *eventOnDate = [store eventsMatchingPredicate:predicateForEventOnDate]; NSLog(@"eventOnDate: %@", eventOnDate); BOOL eventExists = NO; for (EKEvent *eventToCheck in eventOnDate) { if ([eventToCheck.title isEqualToString:eventTitle]) { eventExists = YES; } } return eventExists; }
When I go through this method, I notice that the NSArray is called eventOnDate nil ( EKEventStore not nil ). I do not know if this means that he simply did not find matching events or something else was happening.
What am I doing wrong that will not allow this to identify existing events in the calendar? Thanks!
source share