Reputation: 31
I'm facing some problems with creating a new calendar inside a Swift program. This code snippet almost works perfectly:
func createNewCalendar(withName name: String) {
let eventStore = EKEventStore()
let calendar = EKCalendar(for: .event, eventStore: eventStore)
calendar.title = name
calendar.cgColor = UIColor.purple.cgColor
guard let source = eventStore.defaultCalendarForNewEvents?.source else {
return
}
calendar.source = source
try! eventStore.saveCalendar(calendar, commit: true)
}
But in some rare cases it fails in the simulator. In this case eventStore.defaultCalendarForNewEvents
is nil
the guard
-command detects this error situation correctly and the method exits without creating a new calendar.
I tried to figure out the right way to handle this situation. Unfortunately I was not able to find a recommendation at the Apple developer section.
So what it the correct code-snippet inside the guard to create a new source for the newly created EKCalendar instance?
Upvotes: 0
Views: 159
Reputation: 2061
The default is an optional, so if not, then you can pick some other way.
(Keep in mind, the preference is really about "new events", not where calendars are created.)
If there is one one source, I think you could just create in it, depending on the situation.
If there are several, you could pick, with the obvious risks.
In my mind, the code should be prepared to fail when all sensible options are exhausted.
Upvotes: 0