新的EventKit EKCalendar不会创建?

时间:2015-06-15 19:05:41

标签: ios macos swift icalendar eventkit

我正在尝试在OS X上创建一个新日历。我无法在日历中显示日历(newcalendar)。我运行代码,打开我的日历,它没有显示。有谁知道为什么?这是我在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 个答案:

答案 0 :(得分:1)

requestAccessToEntityType在另一个线程中异步运行。您需要将完成与信号量同步。我是这样做的:

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