I'm trying to find a way to retrieve the email account associated to calendar events on the Mac. Is there a way to do that?
I tried looking in to the EKEvent
object and it does not indicate the email account. I also tried looking in to the ACAccountStore
.
This is the swift code I used to retrieve the events:
func fetchCalendarEvents() {
// Step 1: Create an instance of EKEventStore
let eventStore = EKEventStore()
// Step 2: Request access to the user's calendars
eventStore.requestAccess(to: .event) { granted, error in
if granted {
// Step 3: Fetch the user's default calendar
let defaultCalendar = eventStore.defaultCalendarForNewEvents
// Step 4: Create a predicate to fetch events from today onwards
let predicate = eventStore.predicateForEvents(withStart: Date(), end: Date().addingTimeInterval(365 * 24 * 60 * 60), calendars: [defaultCalendar!])
// Step 5: Fetch the events using the predicate
let events = eventStore.events(matching: predicate)
}
}
}
Ok so what I found is that IF there are attendees for an Event, I'm able to retrieve the email from the EKEvent.Organizer property. The Organizer is of type EKParticipant and there's a property EKParticipant.IsCurrentUser that indicates if the participant is the account owner. The rest of the attendees are listed in EKEvent.Attendees and if the Organizer is not the current user, one of the other attendees must be.
The only caveat to this approach is the event must have at least one attendee.
The code below works for Google, iCloud or Exchange accounts:
for ekEv in ekEvents {
if let organizer = ekEv.organizer, organizer.isCurrentUser {
let email = organizer.url?.resourceSpecifier
}
}