iosxcodecalendareventkit

Avoid iOS EventKit startDate and endDate overlapping with existing events


I can successfully add some events to the Calendar, using this simple code snippet:

 var eventStore : EKEventStore = EKEventStore()
        eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {
            granted, error in
            if (granted) && (error == nil) {
                println("Access granted to calendar \(granted)")
                println("No error or error is simply \(error)")
                
                var event:EKEvent = EKEvent(eventStore: eventStore)
                event.title = fullTitle
                event.startDate = startDate
                event.endDate = endDate
                event.notes = "This is a note"
                event.calendar = eventStore.defaultCalendarForNewEvents
                eventStore.saveEvent(event, span: EKSpanThisEvent, error: nil)
                println("Saved Event")
            }

I can handle errors and authorisation issues, but I want to be sure that there's no overlap, not even by a minute when I add a new Calendar event with an existing one.

By default it just "overload", I could set many events at the very same time but I don't want this behaviour... So, what I mean is that startDate and endDate should be set on an empty slot, if something is already set in between I want to be notified in advance.

I read the EventKit documentation but is kind of cumbersome to me, also the examples I found vary in galore from the code I got, which is working fine.


Solution

  • You can search if the event exists before you save it. If the event exists just doesn't add it.

    To find if event exists you can use something like:

    NSString *predicateString= [NSString stringWithFormat:@"title == '%@' AND location == '%@' AND notes == '%@'", event.title, event.location, event.notes ];
        
        NSPredicate *matches = [NSPredicate predicateWithFormat:predicateString];
        
        NSArray *datedEvents = [self.eventStore eventsMatchingPredicate:[eventStore predicateForEventsWithStartDate:event.startDate endDate:event.endDate calendars:nil]]; //search in all calendars
        
        NSArray *matchingEvents = [datedEvents filteredArrayUsingPredicate:matches];