Search code examples
iosmacosswiftcalendareventkit

Returning a single calendar with calendarWithIdentifier


I'm trying to call a method that will get a calendar when creating an event. This method I'm sure is meant to use calendarWithIdentifier which gets the ID of the

Here's my code for the creating the event and calling the method that will get the calendar. I need to call a specific calendar

var store = EKEventStore()

func applicationDidFinishLaunching(aNotification: NSNotification) {
// ask for permission
// call methods
}

// Create new calendar
func createCalendar() -> EKCalendar? {
    var calendar = EKCalendar(forEntityType: EKEntityTypeEvent, eventStore: self.store)
    calendar.title = "Calendarname"
    // ...
    return calendar
}

func createEvent(){      
    var newEvent : EKEvent = EKEvent(eventStore: store)
    var error : NSError? = nil
    newEvent.title = "day off"
    newEvent.location = "London"

    var startDate : String = "2015-07-16";
    var dateFmt1 = NSDateFormatter()
    dateFmt1.dateFormat = "yyyy-MM-dd"
    var date1:NSDate = dateFmt1.dateFromString(startDate)!;

    var endDate : String = "2015-07-17";
    var dateFmt2 = NSDateFormatter()
    dateFmt2.dateFormat = "yyyy-MM-dd"
    var date2:NSDate = dateFmt2.dateFromString(endDate)!;

    newEvent.startDate = date1
    newEvent.endDate = date2
    newEvent.notes = "testing the event"
    newEvent.calendar = getCalendar()

    self.store.saveEvent(newEvent, span: EKSpanThisEvent, commit: true, error: nil)

}

func getCalendar() -> EKCalendar? {
  // ...
}

I'm aware of this

func calendarWithIdentifier(_ identifier: String!) -> EKCalendar!

which is from Apple's EventKit Documentation used to return a calendar by id. So I'm using the Calendar's name ("Calendarname") as the argument, but this doesn't seem to be right. It's returning nil.

Can someone help me get the Calendar correctly? Thank you


Solution

  • I was able to get it working. Here's the getCalendar function now:

    func getPSACalendar() -> EKCalendar{
        var calUID:String = "?"
        var cal =  store.calendarsForEntityType(EKEntityTypeEvent) as [EKCalendar]
        for i in cal {
            if i.title == "Calendarname" {
                calUID = i.calendarIdentifier
            }
        }
        var calendar = store.calendarWithIdentifier(calUID)
        return calendar
    }