一些问题:
您的代码崩溃了,因为您first
从一个空的数组中强制解包.以下是一些建议,以确保EKSource
对象数组返回非空数组.
首先,要求用户访问使用他们的日历requestAccess(to:)
上的一个EKEventStore
实例.其次,使用an 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 } }