我正在尝试创建日历,而不是日历事件而是日历.我无法获得本地来源,我的应用程序崩溃了.
这是我的代码:
let newCalendar = EKCalendar(for: .event,eventStore: eventStore) newCalendar.title = "Some Calendar Name" let sourcesInEventStore = eventStore.sources newCalendar.source = sourcesInEventStore.filter{ (source: EKSource) -> Bool in source.sourceType.rawValue == EKSourceType.local.rawValue }.first!
我完全关闭了我的iCloud,仍然无法获得本地资源.
我也试图让这个与iCloud打开工作,我想出了这个代码,但它不起作用
for let source in eventStore.sources { if(source.sourceType == EKSourceType.calDAV && source.title == "iCloud") { newCalendar.source = source } } if(newCalendar.source == nil) { for let source2 in eventStore.sources { if(source2.sourceType == EKSourceType.local) { newCalendar.source = source2 } } }
解决方法
一些问题:
您的代码崩溃了,因为您首先从空数组中强制解包.以下是一些建议,以确保EKSource对象数组返回非空数组.
首先,要求用户使用EKEventStore实例上的requestAccess(to :)访问其日历.其次,使用if let从过滤后的数组中展开可能的可选值:
let eventStore = EKEventStore() eventStore.requestAccess(to: .event) { (granted,error) in if granted { let newCalendar = EKCalendar(for: .event,eventStore: eventStore) newCalendar.title = "Some Calendar Name" let sourcesInEventStore = eventStore.sources let filteredSources = sourcesInEventStore.filter { $0.sourceType == .local } if let localSource = filteredSources.first { newCalendar.source = localSource } else { // Somehow,the local calendar was not found,handle error accordingly } } else { // check error and alert the user } }