I am trying create a new calendar, not a claendar event, a new calendar.
I found a tutorial online and came up with this code:
// Create an Event Store instance
let eventStore = EKEventStore();
// Use Event Store to create a new calendar instance
// Configure its title
let newCalendar = EKCalendar(for: .event, eventStore: eventStore)
// Probably want to prevent someone from saving a calendar
// if they don't type in a name...
newCalendar.title = "Some Calendar Name"
// Access list of available sources from the Event Store
let sourcesInEventStore = eventStore.sources
// Filter the available sources and select the "Local" source to assign to the new calendar's
// source property
newCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
// Save the calendar using the Event Store instance
do {
try eventStore.saveCalendar(newCalendar, commit: true)
UserDefaults.standard.set(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar")
delegate?.calendarDidAdd()
self.dismiss(animated: true, completion: nil)
} catch {
let alert = UIAlertController(title: "Calendar could not save", message: (error as NSError).localizedDescription, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
The problem is the app crashes with an error of: fatal error: unexpectedly found nil while unwrapping an Optional value.
I did some debugging and found it was this line that is crashing:
newCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
It appears that my EKEventStore sources are empty.
I added this to my plist - Privacy - Calendars Usage Description Value & Privacy - Calendars Usage Description (Privacy - Calendars Usage Description with $(PRODUCT_NAME) calendar events but my app still crashes, please help.
UPDATE
My iCloud is completely turned off, I am 100% signed out of iCloud, still no local source, I get the same error.