
Creating and saving calendar events
Create and configure calendar events to save them to the user calendar.
If you need to create an event in a user’s calendar from a SwiftUI app, you can use the EventKit framework. EventKit provides native access to the Calendar app so you can create, read, and manage events directly.
Before interacting with the calendar, you must declare the reason for access in your app’s Info.plist.
Add the following key with a user-facing description:
Privacy – Calendars Full Access Usage Description
(NSCalendarsFullAccessUsageDescription)
This message is shown when iOS asks for the user’s permission.
The main entry point for calendar operations is EKEventStore
Create a single instance of it and reuse it whenever possible.
import EventKit
let eventStore = EKEventStore()
On iOS 17+, use requestFullAccessToEvents()
to request full
do {
let granted = try await eventStore.requestFullAccessToEvents()
if granted {
print("Permission granted.")
} else {
print("Permission denied.")
}
} catch {
print("Error requesting access: \(error.localizedDescription)")
}
Note: This method is asynchronous because it depends on user interaction.
Once you have permission, create a new EKEvent
linked to your event store:
let event = EKEvent(eventStore: eventStore)
Set the event details, such as title, start date, end date, and the calendar to save it in. The default calendar for new events can be retrieved via eventStore.defaultCalendarForNewEvents
.
event.title = "Important Appointment"
event.startDate = Date() // Replace with your desired start date
event.endDate = Date().addingTimeInterval(3600) // 1 hour later
event.calendar = eventStore.defaultCalendarForNewEvents
Save the event using save(_:span:)
. The span parameter specifies whether you are saving only this instance (thisEvent
) or future instances of a recurring event (futureEvents
).
do {
try eventStore.save(event, span: .thisEvent)
print("Event saved!")
} catch {
print("Error saving event: \(error.localizedDescription)")
}