Search code examples
iosswifteventkit

Adding events and calendars with EventKit


I need to add a event to the users calendar.

So i get all his calendars with:

let calendars = store.calendarsForEntityType(EKEntityTypeEvent)
        as [EKCalendar]

I have a few problems:

  1. how do i know to what calendar to add the event
  2. I can show the user all his calendars and ask him to choose, but in this list i get [calendar, calendar, birthdays, birthdays] i get each calendar twice, so what one do i take?
  3. is there a way to add a new calendar for adding events?

Thanks


Solution

  • In order to create a new calendar, you should create it and store the id in NSUserDefaults so you can retrieve it next time. I use the following function to fetch the calendar if it exists and create it if it does not:

    func getCalendar() -> EKCalendar? {
        let defaults = NSUserDefaults.standardUserDefaults()
    
        if let id = defaults.stringForKey("calendarID") {
            return store.calendarWithIdentifier(id)
        } else {
            var calendar = EKCalendar(forEntityType: EKEntityTypeEvent, eventStore: self.store)
    
            calendar.title = "My New Calendar"
            calendar.CGColor = UIColor.redColor()
            calendar.source = self.store.defaultCalendarForNewEvents.source
    
            var error: NSError?
            self.store.saveCalendar(calendar, commit: true, error: &error)
    
            if error == nil {
                defaults.setObject(calendar.calendarIdentifier, forKey: "calendarID")
            }
    
            return calendar
        }
    }
    

    Now you use this calendar when creating a new event so you can add the event to this calendar:

    func addEvent() {
        var newEvent = EKEvent(eventStore: self.store)
        newEvent.title = someTitle
        newEvent.location = someLocation
        newEvent.startDate = someStartDate
        newEvent.endDate = someEndDate
        newEvent.notes = someMoreInfo
        newEvent.calendar = getCalendar()
    
        self.store.saveEvent(newEvent, span: EKSpanThisEvent, commit: true, error: nil)
    }