Fetching events from the user’s calendar

Fetching events from the user’s calendar

Learn how to retrieve events between specific dates from the calendar.

To query and return events from the user’s calendar on the device to your apps, you need to connect to the event store and fetch them with a predicate. It will return zero or more events, which you can then work with within the logic of your app.

To do this, you need the user's permission to access the events and possibly create an event on their calendar.

import EventKit

let eventStore = EKEventStore()

func requestAccess() async -> Bool {
    do {
        let granted = try await eventStore.requestFullAccessToEvents()
        return granted
    } catch {
        return false
    }
}

To retrieve events, create a search predicate that acts as a filter, defining date ranges and from which calendars to get the events from. Use the method predicateForEvents(withStart:end:calendars:) from the event store to create a predicate.

let calendars = eventStore.calendars(for: .event)
let oneMonthAgo = Date()
let oneMonthAfter = Calendar.current.date(byAdding: .month, value: 1, to: Date())!

let predicate = eventStore.predicateForEvents(
    withStart: oneMonthAgo,
    end: oneMonthAfter,
    calendars: calendars
)

Use the created predicate to fetch events from the events store using the events(matching:) method, which returns an array of EKEvent objects matching the predicate.

let events = eventStore.events(matching: predicate)
    .sorted { $0.startDate < $1.startDate }

await MainActor.run {
    self.events = events
}