我可以使用以下功能创建新日历并保存:
func createCalendarForUser() {
let sourcesInEventStore = self.eventStore.sources
//works but doesn't persist
let subscribedSourceIndex = sourcesInEventStore.index {$0.title == "Subscribed Calendars"}
if let subscribedSourceIndex = subscribedSourceIndex {
let userCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
userCalendar.title = "newCalendar"
userCalendar.source = sourcesInEventStore[subscribedSourceIndex]
do {
try self.eventStore.saveCalendar(userCalendar, commit: true)
print("calendar creation successful")
} catch {
print("cal \(userCalendar.source.title) failed : \(error)")
}
}
}
当应用程序打开并运行时,此功能很棒。我可以将事件保存给他们,我可以在我的本地日历中看到它们,生活也很美好。但是,一旦应用程序终止并进入后台,日历就会消失,同时在其中创建任何事件。我尝试将日历保存到除Subscribed Calendars
来源之外的其他来源,但是当我这样做时,日历甚至不会保存在第一位。以下是使用本地来源的尝试之一:
func createCalendarForUser() {
let sourcesInEventStore = self.eventStore.sources
//never saves calendar
let localSourceIndex = sourcesInEventStore.index {$0.sourceType == .local}
if let localSourceIndex = localSourceIndex {
let userCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
userCalendar.title = "newCalendar"
userCalendar.source = sourcesInEventStore[localSourceIndex]
do {
try self.eventStore.saveCalendar(userCalendar, commit: true)
print("creating new calendar successful")
} catch {
print("creating new calendar failed : \(error)")
}
}
}
我也尝试过这种方法:
func createCalendarForUser() {
let sourcesInEventStore = self.eventStore.sources
//doesnt work
let userCalendar = EKCalendar(for: .event, eventStore: self.eventStore)
userCalendar.title = "newCalendar"
userCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.local.rawValue
}.first!
do {
try self.eventStore.saveCalendar(userCalendar, commit: true)
print("creating new calendar succesful")
} catch {
print("creating new calendar failed : \(error)")
}
}
正如这里提到的那样https://www.andrewcbancroft.com/2015/06/17/creating-calendars-with-event-kit-and-swift/
还有其他人遇到过这个问题吗?
答案 0 :(得分:0)
您链接的博客文章在保存日历时会执行两项操作,它使用saveCalendar(, commit)
方法将日历保存到事件存储区,然后还将日历的标识符保存到用户默认值,以便它可以在以后检索:
NSUserDefaults.standardUserDefaults().setObject(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar")
您正在执行第一步,但不执行第二步,因此您的日历将保留在商店中,但您并未保留检索它们所需的信息未来。