【发布时间】:2018-02-12 05:40:51
【问题描述】:
在刷新我的集合视图之前,我需要依次运行两个函数。第一个函数从 firebase 中提取 autoids 并将它们写入一个数组。然后第二个函数 (getLocation) 使用该数组再次调用 firebase 以检索每个 autoid 下的值(位置)。
我使用 DispatchGroup() 来确保第一个函数在第二个函数开始之前完成。但我还需要在通知刷新集合视图之前完成第二个功能。
我已经编写了一个基本的 for 循环来测试第二个函数中的 DispatchGroup() 并且能够让它执行,但是当我使用它从 firebase 实际获取数据时我无法让它正常工作。
想知道我是否会在错误的地方进出?这是我的功能。
调度组
let dispatchGroup = DispatchGroup()
功能:
func getLocation() {
self.dispatchGroup.enter()
for i in 0..<self.eventsArray.count {
let eventid = self.eventsArray[i]
self.ref.child("Events").child(eventid).observe(.value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let location = dictionary["location"] as! String
self.locationsArray.append(location)
} })
}
self.dispatchGroup.leave()
}
func getEvents() {
self.dispatchGroup.enter()
Database.database().reference().child("Events").observe(DataEventType.value, with: { (snapshot) in
if let dictionary = snapshot.children.allObjects as? [DataSnapshot] {
for child in dictionary {
let eventid = child.key
self.eventsArray.append(eventid)
}
self.dispatchGroup.leave()
} })
}
所以我调用每个函数然后使用 dispatchGroup.notify。
getEvents()
getLocation()
dispatchGroup.notify(queue: .main) {
print(self.locationsArray)
self.eventsCollectionView.reloadData()
}
这是我第一次使用 DispatchGroups,因此欢迎任何提示或建议。
【问题讨论】:
-
记录在案的解决方案:stackoverflow.com/a/40004392/3890944
标签: swift firebase firebase-realtime-database grand-central-dispatch