Dustin Spengler Dustin Spengler - 2 months ago 15
iOS Question

Appropriate situations to create new EKCalendar iOS

I am working on an iOS app which creates, updates, and deletes

EKEvents
. This can easily be accomplish by saving the events to
EKEventStore.defaultCalendarForNewEvents
. Under what circumstance would I want create a new
EKCalendar
for my own app and what functionality does that entail?

I am asking because I am currently trying to create a calendar in Swift 3.0 and it keeps failing, which leaves me wandering what the purpose of the new calendar is in the first place.

fileprivate var eventStore = EKEventStore()
fileprivate var newCalendar : EKCalendar?

func createNewCalendar() {
self.newCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
self.newCalendar!.title = "newCal"
let sourcesInEventStore = self.eventStore.sources
self.newCalendar!.source = eventStore.defaultCalendarForNewEvents.source

let newCalIndex = sourcesInEventStore.index {$0.title == "newCal"}
if newCalIndex == nil {
do {
try self.eventStore.saveCalendar(self.newCalendar!, commit: true)
print("cal succesful")
} catch {
print("cal failed")
}
}
}


I know i have access to the
eventStore
because I can pull in events as well as save them to the
EKEventStore.defaultCalendarForNewEvents
and update them using their existing calendar.

Answer

There might be many reasons why you might want to create a new calendar. Personally, I choose to create a new calendar when I want to separate some group of events from the ones created within the default calendar. By this way, you also take advantage of bulk deleting of those newly created events when you think you don't need them. Just delete the calendar and all of its events will be purged as well.

By the way, if you are not sure what should be the source (iCloud, local, maybe tied to some mail account etc.) of the new calendar you want to create, just use the source of default calendar:

let newCalendar = EKCalendar(forEntityType: .Event, eventStore: eventStore)
newCalendar.source = eventStore.defaultCalendarForNewEvents.source

Also make sure default calendar's allowsContentModifications property returns true if you want to use its source.