
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 device from 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 be able to do it, you need the user's permission to access the events and possibly create an event on the user's 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.
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 predicate to fetch events from the events store using the events(matching:)
method.
let events = eventStore.events(matching: predicate)
.sorted { $0.startDate < $1.startDate }
await MainActor.run {
self.events = events
}