Search code examples
iphoneioseventsalarm

Creating a calendar event with an alarm using EKEventEditViewController


I'm using the following code to create an event, and display a popup asking the user to save the event:

EKEventStore *eventStore = [[EKEventStore alloc] init];
EKCalendar *calendar = [eventStore defaultCalendarForNewEvents];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.calendar = calendar;
event.title = [NSString stringWithFormat:@"Event: %@", [self.event title]]; 
event.location = self.event.location;
event.notes = [self stringByStrippingHTML: [self.event description]];
event.startDate = [self.event startDate]; 
event.endDate = [self.event endDate];

NSTimeInterval alarmOffset = -1*60*60;//1 hour
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:alarmOffset];

[event addAlarm:alarm];
EKEventEditViewController *eventViewController = [[EKEventEditViewController alloc] init];
eventViewController.event = event;
eventViewController.eventStore=eventStore;
eventViewController.editViewDelegate = self;
[self.navigationController presentModalViewController:eventViewController animated:YES];

This works fine except the event alarm property doesn't get set as you can see form the image below:

Alarm Not Set

If I save the event before showing the view controller it does get the alarm set.

Please note I'm using the LLVM compiler, so don't worry about not releasing stuff!

Ta

Ross


Solution

  • Finally found out how to do it.

    Your controller would have to implement the protocol UINavigationControllerDelegate, and set the EKEventEditViewController delegate to self. Then just implement the

    navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated

    method and add the alarm there.

    Here is my implementation.

    - (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    
        if ([navigationController isKindOfClass:[EKEventEditViewController class]]) {
          EKEventEditViewController *ek = (EKEventEditViewController*)navigationController;
          EKEvent *event = ek.event;
          // set alarm to 15 mins prior of the event if it starts later than 15 mins out
          if ([event.startDate compare:[[NSDate date] dateByAddingTimeInterval:60*15]] != NSOrderedAscending) { 
            EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:60*15*-1];
            event.alarms = [NSArray arrayWithObject:alarm];
          }    
        }
    }