New EventKit EKCalendar will not create?

675 views Asked by At

I am trying to create a new calendar on OS X. I cannot get the calendar (newcalendar) to show in my calendar. I run the code, open my Calendar and it doesn't show. Does anyone have any idea why? Here's what I have in my AppDelegate.swift:

var store = EKEventStore()

// creating the new calendar
func getCalendar() -> EKCalendar? {
     println("5")
    let defaults = NSUserDefaults.standardUserDefaults()

    if let id = defaults.stringForKey("calendarID") {
        return store.calendarWithIdentifier(id)
         println("6")
        }
    else {
        var calendar = EKCalendar(forEntityType: EKEntityTypeEvent, eventStore: self.store)
            println("6")
        calendar.title = "newcalendar"
        calendar.color = NSColor.brownColor()
        calendar.source = self.store.defaultCalendarForNewEvents.source

    println("7")
    var error: NSError?
    self.store.saveCalendar(calendar, commit: true, error: &error)
    println("8")

    if error == nil {
        defaults.setObject(calendar.calendarIdentifier, forKey: "calendarID")
    }

    return calendar
    println("9")
    }
}


// Where it starts
func applicationDidFinishLaunching(aNotification: NSNotification) {
  println("1")
var sema = dispatch_semaphore_create(0)
var hasAccess = false

// Ask for permission to access calendars
store.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted:Bool, error:NSError?) in hasAccess = granted; dispatch_semaphore_signal(sema)})

//println("Permission to connect to Calendar = \(success); error? = \(error)")
  println("2")
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
   println("3")
    if (!hasAccess){
    }
    else {
        // returns an array of EKCalendars
        var eventCalendars =
        store.calendarsForEntityType(EKEntityTypeEvent) as [EKCalendar]
        println("4")
        // for each calendar in array, if the calendar is called newcalendar,
        for i in eventCalendars {
            if i.title == "newcalendar" {
                println("newcalendar already exists")
            }
            else {
                getCalendar()
                break
            }
        }
    }
} //end of applicationDidFini...
1

There are 1 answers

2
qwerty_so On

requestAccessToEntityType runs asynchronously in a different thread. You need to synch the completion with a semaphore. I do it like this:

var sema = dispatch_semaphore_create(0)
var hasAccess = false

eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted:Bool, error:NSError?) in hasAccess = granted; dispatch_semaphore_signal(sema) })

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
if (!hasAccess) {
  fatalError....
}
// proceed normally