Setting alarms for calendar events

Setting alarms for calendar events

Learn how to add an alarm to an event that notify users before an event starts.

One of the features of the EventKit framework is to provide users with the option to set alarms for their calendar items. Alarms appear as a notification and remind users of a scheduled calendar event. They can be time-based, triggering at a specific time.

First of all, you need the user's permission to access the events and create an event on the user's calendar.


The alarm can be created when adding a new event, so the time of creation of the event can be used as a reference for the triggering the notification.

let alarm = EKAlarm(relativeOffset: TimeInterval(-600))

event.addAlarm(alarm)

To create a new alarm use the EKAlarm class. The initializer EKAlarm(absoluteDate:) crates an alarm that triggers on a precise date, while the initializer EKAlarm(relativeOffset:) sets the trigger of the alarm based on the starting date of the event it is associated with.

To associate the alarm with a calendar event use the addAlarm(_:) method. Here is an example of how you can set up an alarm when creating a new event in your application:

import EventKit
import Observation

@Observable
final class CalendarEventManager {

    let eventStore = EKEventStore()
    
    func createEvent(
        title: String,
        startDate: Date,
        endDate: Date,
        alarmLeadMinutes: Int = 10
    ) async {
        // Ensure we have a calendar to save into (user's default for new events).
        guard let targetCalendar = eventStore.defaultCalendarForNewEvents else {
            print("No default calendar available for new events.")
            return
        }
        
        // Create the event and set its primary fields.
        let event = EKEvent(eventStore: eventStore)
        event.title = title
        event.startDate = startDate
        event.endDate = endDate
        event.calendar = targetCalendar
        
        // Configure a relative alarm that fires N minutes *before* the start.
        // Negative offset = before startDate; positive = after.
        let alarmOffset = TimeInterval(-alarmLeadMinutes * 60)
        let alarm = EKAlarm(relativeOffset: alarmOffset)
        event.addAlarm(alarm)
        
        do {
            try eventStore.save(event, span: .thisEvent)
            print("Event with alarm was saved.")
        } catch {
            print("Failed to save event: \(error.localizedDescription)")
        }
    }
    
}