2

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

ilan
  • 4,402
  • 6
  • 40
  • 76
  • Are you trying to add an event with or without Apple's EventKitUI framework? – Ian Mar 11 '15 at 18:25
  • I ask because many people know about the EventKit framework, but not the EventKitUI framework which provides a standard modal view controller for adding events – Ian Mar 11 '15 at 18:31
  • thanks, but i need to add events that i get from my server and not from the user – ilan Mar 11 '15 at 18:33

1 Answers1

8

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)
}
Ian
  • 12,538
  • 5
  • 43
  • 62
  • In iOS 8 (and possibly before that) I got the error "Cannot assign a value of type 'UIColor' to a value of type 'CGColor'". Changing to UIColor.redColor().CGColor resolved this for me. – Adam Knights Apr 16 '15 at 12:49
  • Great tip, just missing the access requesting, i found it here http://stackoverflow.com/a/28398477/3027848 – aledustet Aug 14 '15 at 16:01