Skip to content

Instantly share code, notes, and snippets.

@samuelbeek
Last active September 22, 2016 13:00
Show Gist options
  • Save samuelbeek/9610415 to your computer and use it in GitHub Desktop.
Save samuelbeek/9610415 to your computer and use it in GitHub Desktop.
Add and remove iCal events with your iOS app.md
In order for this to work, you need to import Evenkit at the top of your file.
Then you can add the function setiCalEvent to your file and then you can simply use <code> [self setiCalEvent:true]; </code> or <code> [self setiCalEvent:false]; </code>. You don't need yo save any data inside your app to remove them later on, because the app does a search query.
- (void)setiCalEvent:(BOOL)setEvent{
//this will only happen if iCal is enabled
if([[NSUserDefaults standardUserDefaults] boolForKey:@"settingiCal"]) {
// Set the Date and Time for the Event
NSDate *eventDateAndTime = _event.dateTimeGMT;
// Set iCal Event
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = _event.type.name;
event.startDate = eventDateAndTime;
event.location = _event.location.name;
event.endDate = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:event.startDate];
// Check if App has Permission to Post to the Calendar
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
//---- code here when user allows your app to access their calendar.
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
//add event
if (setEvent) {
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}
// remove event
else {
NSLog(@"removeEvent");
// Create the predicate from the event store's instance method
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:event.startDate
endDate:event.endDate
calendars:nil];
// Fetch all events that match the predicate
NSArray *events = [eventStore eventsMatchingPredicate:predicate];
//check if there's events with the same name at this time, remove them.
for(int i = 0; i < [events count]; i++) {
EKEvent *currentEvent = events[i];
NSLog(@"current Event Title: %@", currentEvent.title);
NSLog(@"to be deleted Event Title: %@", _event.type.name);
if([currentEvent.title isEqualToString:_event.type.name]){
NSLog(@"delete stuff");
[eventStore removeEvent:currentEvent span:0 commit:YES error:nil];
}
}
}
}else
{
//----- code here when user does NOT allow your app to access their calendar.
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}
}];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment