I need to add a event to the users calendar.
So i get all his calendars with:
let calendars = store.calendarsForEntityType(EKEntityTypeEvent)
as [EKCalendar]
I have a few problems:
Thanks
In order to create a new calendar, you should create it and store the id in NSUserDefaults so you can retrieve it next time. I use the following function to fetch the calendar if it exists and create it if it does not:
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
}
}
Now you use this calendar when creating a new event so you can add the event to this 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)
}