swiftcolorseventkitekeventekcalendar

Get the Calendar Color from EKEvent in Swift


In Apple's EventKit each Calendar can have a user-definable color, which can also be accessed on the EKCalendar instance as EKCalendar.color. How can that color be accessed from a single event (not a calendar)? Is there any back-reference from an EKEvent instance to the EKCalendar the event belongs to?

As an example, I have a list of calendars and fetch events by start and end date. In the resulting array of events it seems any information answering a question "from which calendar a single event is" got lost.

import EventKit

let eventStore = EKEventStore()
let calendars: [EKCalendar] = getCalendars() // get some calendars here

let d = (start: Date(), end: Date().addingTimeInterval(3600*5)) // [now, now+5h]
let predicate = eventStore.predicateForEvents(withStart: d.start, end: d.end, calendars: calendars)

let events = eventStore.events(matching: predicate) // fetch the events

for event in events { // iterate over all events from calendars within [now, now+5h]
   // ?? how to get the color of the calendar of event? or
   // ?? how to get the EKCalendar instance event is from?
}

Solution

  • It looks like EKEvent is a subclass of EKCalendarItem. The EKCalendarItem contains a property, calendar.

    That being said, here's the answers to the questions

    ...
    for event in events { // iterate over all events from calendars within [now, now+5h]
       // ?? how to get the color of the calendar of 
       let color = event.calendar.color
    
       // ?? how to get the EKCalendar instance event is from?
       let calendar = event.calendar
    }