O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

16.2. Adding Events to Calendars

Problem

You would like to be able to create new events in users’ calendars.

Solution

Find the calendar you want to insert your event into (please refer to Recipe 16.1). Create an object of type EKEvent using the eventWithEventStore: class method of EKEvent and save the event into the user’s calendar using the saveEvent:span:error: instance method of EKEventStore:

- (BOOL)    createEventWithTitle:(NSString *)paramTitle
                       startDate:(NSDate *)paramStartDate
                         endDate:(NSDate *)paramEndDate
             inCalendarWithTitle:(NSString *)paramCalendarTitle
              inCalendarWithType:(EKCalendarType)paramCalendarType
                           notes:(NSString *)paramNotes{

  BOOL result = NO;

  EKEventStore *eventStore = [[EKEventStore alloc] init];

  /* Are there any calendars available to the event store? */
  if ([eventStore.calendars count] == 0){
    NSLog(@"No calendars are found.");
    return NO;
  }

  EKCalendar *targetCalendar = nil;

  /* Try to find the calendar that the user asked for */
  for (EKCalendar *thisCalendar in eventStore.calendars){
    if ([thisCalendar.title isEqualToString:paramCalendarTitle] &&
        thisCalendar.type == paramCalendarType){
      targetCalendar = thisCalendar;
      break;
    }
  }

  /* Make sure we found the calendar that we were asked to find */
  if (targetCalendar == nil){
    NSLog(@"Could not find the requested calendar.");
    return NO;
  }

  /* If a calendar does not allow modification of its contents
   then we cannot insert an event into it */
  if (targetCalendar.allowsContentModifications == NO){
    NSLog(@"The selected calendar ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required