创建日历,即使关闭 iCloud 也没有本地资源
Create Calendar, no local source even with iCloud off
我正在尝试创建日历,不是日历事件而是日历。我无法获取本地资源,我的应用程序崩溃了。
这是我的代码:
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
}
}
}
几个问题:
您的代码正在崩溃,因为您 force-unwrapping first
来自一个空数组。以下是确保 EKSource
对象数组 returns 为 non-empty 数组的一些建议。
首先,要求用户在 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 { [=10=].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
}
}
我正在尝试创建日历,不是日历事件而是日历。我无法获取本地资源,我的应用程序崩溃了。
这是我的代码:
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
}
}
}
几个问题:
您的代码正在崩溃,因为您 force-unwrapping first
来自一个空数组。以下是确保 EKSource
对象数组 returns 为 non-empty 数组的一些建议。
首先,要求用户在 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 { [=10=].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
}
}