How to create an iCloud Calendar?

I'm trying to create a calendar for my iOS app to place events into. I've seen some people simply grab all the calendars on the device and write to the first one that is writable, but I really dislike that. I don't want to screw around with my users' existing calendars.


In pseudocode, this is what I want:


if (calendar exists) {

add event

}

else {

create calendar

add event

}


That "create calendar" line is really giving me trouble. I can't find anything online or in the documentation to do that with swift. Any help?


Thanks!

This is my solution. I didn't take into account any error catching, but I put the variables in for if it was needed.


func checkCalendar() -> EKCalendar {
        var retCal: EKCalendar?
     
        let calendars = eventStore.calendarsForEntityType(EKEntityTypeEvent) as! [EKCalendar] // Grab every calendar the user has
        var exists: Bool = false
        for calendar in calendars { // Search all these calendars
            if calendar.title == "Auto Schedule Cal" {
                exists = true
                retCal = calendar
            }
        }
     
        var err : NSError?
        if !exists {
            let newCalendar = EKCalendar(forEntityType:EKEntityTypeEvent, eventStore:eventStore)
            newCalendar.title="Auto Schedule Cal"
            newCalendar.source = eventStore.defaultCalendarForNewEvents.source
            eventStore.saveCalendar(newCalendar, commit:true, error:&err)
            retCal = newCalendar
        }
     
        return retCal!
     
    }


This functions searches for a calendar named "Auto Schedule Cal". If it doesn't find it, it creates one. It then returns the calender for use.


Usage:

(Given an EKEventStore titled "store")


let currentCal = checkCalendar()
var calEvent = EKEvent(eventStore: store)
calEvent.calendar = currentCal


You can then set up events on the new calendar!

How to create an iCloud Calendar?
 
 
Q