我需要在用户日历中添加一个事件。
所以我得到了他所有的日历:
let calendars = store.calendarsForEntityType(EKEntityTypeEvent)
as [EKCalendar]
我有一些问题:
由于
答案 0 :(得分:6)
为了创建新日历,您应该创建它并将该ID存储在NSUserDefaults中,以便下次可以检索它。我使用以下函数来获取日历(如果存在),如果不存在则创建日历:
func getCalendar() -> EKCalendar? {
let defaults = NSUserDefaults.standardUserDefaults()
if let id = defaults.stringForKey("calendarID") {
return store.calendarWithIdentifier(id)
} else {
var calendar = EKCalendar(forEntityType: EKEntityTypeEvent, eventStore: self.store)
calendar.title = "My New Calendar"
calendar.CGColor = UIColor.redColor()
calendar.source = self.store.defaultCalendarForNewEvents.source
var error: NSError?
self.store.saveCalendar(calendar, commit: true, error: &error)
if error == nil {
defaults.setObject(calendar.calendarIdentifier, forKey: "calendarID")
}
return calendar
}
}
现在,您在创建新事件时使用此日历,以便将事件添加到此日历中:
func addEvent() {
var newEvent = EKEvent(eventStore: self.store)
newEvent.title = someTitle
newEvent.location = someLocation
newEvent.startDate = someStartDate
newEvent.endDate = someEndDate
newEvent.notes = someMoreInfo
newEvent.calendar = getCalendar()
self.store.saveEvent(newEvent, span: EKSpanThisEvent, commit: true, error: nil)
}