Returning a single calendar with calendarWithIdentifier

1.2k views Asked by At

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

2

There are 2 answers

0
Yelims01 On BEST ANSWER

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
}
1
qwerty_so On

The method calendarWithIdentifier expects a UID rather than a readable name. You need to retrieve them from your store like this:

var calUid:String = "?"
for cal in store.calendarsForEntityType(EKEntityTypeEvent) { 
  if cal.title == "Calendarname" { calUid = cal.calendarIdentifier }
}

and later you can use it like

calendar = store.calendarWithIdentifier(calUid)