我需要在Swift的某一天获得一系列事件。因为EKEventStore.requestAccessToEntityType
是异步运行的,所以我使用dispatch_group_notify
等待EKEventStore.requestAccessToEntityType
的完成处理程序完成,所以我可以用它做一些事情然后返回它。但我无法从闭包中的函数返回我传递给dispatch_group_notify
,因为它尝试从闭包返回,而不是函数。这是我的代码
class func eventsOn(date: NSDate) -> [Event] {
var events = [Event]()
var ekEvents = [EKEvent]()
var dispatch_group = dispatch_group_create()
dispatch_group_enter(dispatch_group)
Event.eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {
gotAccess, error in
let cal = NSCalendar.currentCalendar()
var comps = cal.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: date)
let aFewHoursAgo = NSDateComponents()
aFewHoursAgo.hour = -5
var daStartDate = cal.dateFromComponents(comps)!
daStartDate = cal.dateByAddingComponents(aFewHoursAgo, toDate: daStartDate, options: .allZeros)!
var aDay = NSDateComponents()
aDay.day = 1
var daEndDate = cal.dateByAddingComponents(aDay, toDate: daStartDate, options: .allZeros)!
daEndDate = daEndDate.dateByAddingTimeInterval(-1)!
let p = Event.eventStore.predicateForEventsWithStartDate(daStartDate, endDate: daEndDate, calendars: [Event.eventStore.defaultCalendarForNewEvents])
let tmp = Event.eventStore.eventsMatchingPredicate(p) as [EKEvent]?
if let _ = tmp {
ekEvents = tmp!
}
dispatch_group_leave(dispatch_group)
})
let queue = dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)
dispatch_group_notify(dispatch_group, queue) {
println(ekEvents)
let ekEventId = Expression<String>("ekEventId")
let eventId = Expression<Int>("id")
for ekEvent in ekEvents {
let daEventId = Event.db["events"].filter(ekEventId == ekEvent.eventIdentifier).select(eventId).first![eventId]
events.append(Event.eventWithId(daEventId)!)
}
return events
}
}
所以我将return events
放在我传递给dispatch_group_notify
的块中,它试图从闭包返回,但我想从函数返回。我怎么能这样做?