O'Reilly logo

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

19.8. 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:

- (void) addAlarmToCalendar:(EKCalendar *)paramCalendar
                    inStore:(EKEventStore *)paramStore{


    /* The event starts 60 seconds from now */
    NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow:60.0];

    /* And end the event 20 seconds after its start date */
    NSDate *endDate = [startDate dateByAddingTimeInterval:20.0];

    EKEvent *eventWithAlarm = [EKEvent eventWithEventStore:paramStore];

    eventWithAlarm.calendar = paramCalendar;
    eventWithAlarm.startDate = startDate;
    eventWithAlarm.endDate = endDate;

    /* The alarm goes off 2 seconds before the event happens */
    EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:-2.0];

    eventWithAlarm.title = @"Event with Alarm";
    [eventWithAlarm addAlarm:alarm];

    NSError *saveError = nil;

    if ([paramStore saveEvent:eventWithAlarm
                         span:EKSpanThisEvent
                        error:&saveError]){
        NSLog(@"Saved an event that fires 60 seconds from now.");
    } else {
        NSLog(@"Failed to save the event. Error = %@", saveError);
    }

}

For information about event stores and calendars and the way to retrieve instances to them, please see Recipe 19.2.

Discussion

An event of type EKEvent can have multiple alarms. Simply create the alarm using either the alarmWithAbsoluteDate: or alarmWithRelativeOffset: class method of EKAlarm. The former ...

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