Skip to content

Instantly share code, notes, and snippets.

@tkaravou
Last active September 29, 2022 13:06
Show Gist options
  • Save tkaravou/e0e84740fe139ad23d36a430a5aca8f8 to your computer and use it in GitHub Desktop.
Save tkaravou/e0e84740fe139ad23d36a430a5aca8f8 to your computer and use it in GitHub Desktop.
How to add an event to a Calendar using Swift/SwiftUI
// You will need to add `Privacy - Calendars Usage Description` as a key in your plist file.
// If you don't have a plist file, click on your project's name > Info and add the key there
// The value should be a brief description as to why you need access to the calendar
// This gist will create the event as soon as the view is loaded
// You'll want to attach it to a button or an action instead
// Place the following code in one of your SwiftUI View files
let store = EKEventStore()
let calendarName = "My Swift Calendar"
init() {
switch EKEventStore.authorizationStatus(for: .event) {
case .authorized:
createEvent()
case .denied:
print("Access denied")
case .notDetermined:
// If the user hasn't granted access yet, ask
store.requestAccess(to: .event, completion: {
[self] (granted: Bool, error: Error?) -> Void in
if granted {
self.createEvent()
} else {
print("Access denied")
}
})
default:
print("Default")
}
}
/**
Inserts an event into the calendar
*/
func createEvent() {
let myCal = getCalendar()
let event = EKEvent(eventStore: store)
event.calendar = myCal
event.title = "New Apple Event"
event.url = URL(string: "https://apple.com")
event.startDate = Date()
event.endDate = Date().addingTimeInterval(1 * 60 * 60) // An hour long event
do {
try store.save(event, span: .thisEvent)
}
catch {
print("Error saving event in calendar")
}
}
/**
Returns or creates a calendar
*/
func getCalendar() -> EKCalendar
{
var myCal : EKCalendar?
let calendars = store.calendars(for: .event)
// Find our calendar
myCal = calendars.first(where: { $0.title == calendarName })
// If no calendar was found, create one
if myCal == nil {
myCal = EKCalendar.init(for: .event, eventStore: store)
myCal!.title = calendarName
myCal!.source = store.defaultCalendarForNewEvents?.source
do {
try store.saveCalendar(myCal!, commit: true)
} catch {
print("Error saving event in calendar")
}
}
return myCal!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment