How to load events from user's calendar
In this post let's go over how to load events that user has in their system calendar. Learn about permissions, requesting access and load the events.
Published: June 7, 2020 Sponsored See booksI want to make this example as short as possible so we will cover only the truly necessary stuff.
To load events (represented with the EKEvent
class) you first need a calendar. And to get calendar and read from it, you need permission from user.
Preparation
There is special class EKEventStore
used to request access, getting events, saving them etc. So the first step is to import the framework and create its instance like so:
import EventKit
let eventStore = EKEventStore()
With this ready we can request permissions from the user.
Info.plist keys
You need to add two keys to Info.plist that explain why do you want the access. NSCalendarsUsageDescription
and NSContactsUsageDescription
. The second is needed because you may have shared calendars.
Theoretically in this case we could add just the first but I think it is better to be safe and prevent any unnecessary problems.
Requesting access
Once you added these keys, we can move to requesting access to the calendar:
func requestAccess() {
eventStore.requestAccess(to: .event) { (granted, error) in
if granted {
DispatchQueue.main.async {
// load events
}
}
}
}
If we get access, we can proceed to load events. Otherwise you should show the user some kind of explainer that this feature won't work without access and redirect them to Settings to allow calendar access.
Preparing predicate for events
To load an event we are going once again to use the EKEventStore
instance we already have. We need a special kind of predicate to load the events. We can use event store to create one like this:
let weekFromNow = Date().advanced(by: TimeInterval.week)
let predicate = eventStore.predicateForEvents(withStart: Date(), end: weekFromNow, calendars: nil)
This will create predicate to match events in the upcoming week (or rather upcoming 7day period). TimeInterval.week
is just my extension to simplify things a bit.
If you pass nil
for the calendars
parameter it will search all the available calendars.
Note: The maximum time span for getting events if four years for performance reasons. I think that is more than enough.
Loading events
Once you have a predicate you can get events for it:
let events = eventStore.events(matching: predicate)
And that is the absolute barebone example of loading calendar events in iOS 🙂
The events
result above is an array of EKEvent
each instance represents event in user's calendar. It has title
property, startDate
, endDate
and many more you can use to display the event in your UI.
Comprehensive example
If you are looking for more EKEventKit
examples you can check out my open-source example project showcasing among others how to let user select calendars, how to edit event, add new one.. It is available on GitHub.
Uses: Xcode 12 & Swift 5.3