O'Reilly logo

iOS 5 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

14.7. Adding Alarms to Calendars

Problem

You want to add alarms to the events in a calendar.

Solution

Use the alarmWithRelativeOffset: class method of EKAlarm to create an instance of EKAlarm. Add the alarm to an event using the addAlarm: instance method of EKEvent, like so:

- (EKCalendar *) getFirstModifiableLocalCalendar{ EKCalendar *result = nil; EKEventStore *eventStore = [[EKEventStore alloc] init]; for (EKCalendar *thisCalendar in eventStore.calendars){ if (thisCalendar.type == EKCalendarTypeLocal && [thisCalendar allowsContentModifications]){ return thisCalendar; } } return result; } - (void) addAlarmToCalendar{ EKCalendar *targetCalendar = [self getFirstModifiableLocalCalendar]; if (targetCalendar == nil){ NSLog(@"Could not find the target calendar."); return; } EKEventStore *eventStore = [[EKEventStore alloc] init]; /* The event starts 60 seconds from now */ NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow:60.0f]; /* And end the event 20 seconds after its start date */ NSDate *endDate = [startDate dateByAddingTimeInterval:20.0f]; EKEvent *eventWithAlarm = [EKEvent eventWithEventStore:eventStore]; eventWithAlarm.calendar = targetCalendar; eventWithAlarm.startDate = startDate; eventWithAlarm.endDate = endDate; /* The alarm goes off two seconds before the event happens */ EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:-2.0f]; eventWithAlarm.title = @"Event with Alarm"; [eventWithAlarm addAlarm:alarm]; NSError *saveError = nil; if ([eventStore saveEvent:eventWithAlarm ...

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