-2

I tried to create a calendar from my app. It does not work on an iPhone 6, the app crashed.

Here is my code:

do {
    let calender = EKCalendar(for: .event, eventStore: eventStore)
    calender.title = "MyApp"
    calender.source = eventStore.defaultCalendarForNewEvents.source
    try eventStore.saveCalendar(calender, commit: true)
    userDefaults.set(calender.calendarIdentifier, forKey: calendarIdentifierKey)
    userDefaults.synchronize()
} catch  {
    print("Error occurred while creating calendar ")
}

Update

  1. In the phone the default calendar is set as xxx.gmail.com
  2. And the following error is thrown

    Error occurred while creating calendar 
    
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Vignesh
  • 93
  • 1
  • 7
  • 2
    What's the error? – Ozgur Vatansever Mar 21 '17 at 02:18
  • Calender was not created – Vignesh Mar 21 '17 at 02:31
  • Error occurred while creating calendar fatal error: unexpectedly found nil while unwrapping an Optional value – Vignesh Mar 21 '17 at 02:32
  • Possible duplicate of http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu?s=1|7.2598 – rmaddy Mar 21 '17 at 03:13
  • Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](http://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – Robotic Cat Mar 21 '17 at 03:28
  • Thanks, But it was not the problem. Calendar is not created while the Calendar's default source is Email. i had updated the question. – Vignesh Mar 21 '17 at 03:58

1 Answers1

1

I finally found the answer.

do {
        let calender = EKCalendar(for: .event, eventStore: eventStore)
        calender.title = "MyApp"
        let sourcesInEventStore = eventStore.sources
        let filteredEventStores = sourcesInEventStore.filter{
            (source: EKSource) -> Bool in
            source.sourceType.rawValue == EKSourceType.local.rawValue || source.title.equalsIgnoreCase("iCloud")
        }
        if filteredEventStores.count > 0 {
            calender.source = filteredEventStores.first!
        } else {
            calender.source = sourcesInEventStore.filter{
                (source: EKSource) -> Bool in
                source.sourceType.rawValue == EKSourceType.subscribed.rawValue
                }.first!
        }
        try eventStore.saveCalendar(calender, commit: true)
        userDefaults.set(calender.calendarIdentifier, forKey: calendarIdentifierKey)
        userDefaults.synchronize()
    } catch  {
        print("Error occurred while creating calendar ")
    }
Vignesh
  • 93
  • 1
  • 7