如何在 Swift 3 中创建特定于应用程序的日历

How to create a app specific Calendar in Swift 3

我试图通过我的应用创建日历。它不适用于 iPhone 6,应用程序崩溃了。

这是我的代码:

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 ")
}

更新

  1. 在phone中默认日历设置为xxx.gmail.com
  2. 并抛出如下错误

    Error occurred while creating calendar 
    

终于找到答案了

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 ")
    }