我试图通过调用以下函数从子节点“ PlayerInPool”中获取Firebase中的“玩家”列表
func getPlayersInPool(completion: @escaping (_ success: Bool) -> Void) {
self.handle = self.poolPlayersRef.child(self.pID)observe(.value, with: { snapshot in
// Calling the second function
self.loadPlayersInPool(/*items: items,*/ snapshot: snapshot) { (success) -> Void in
if success {
print("Players Array Count = ", self.players.count)
for j in 0 ..< self.players.count {
print(self.players[j].description)
}
//
//self.actionController.reloadData()
//
completion(true)
}
}
}) { (error) in
print(error.localizedDescription)
}
}
从上述函数调用的第二个函数:
func loadPlayersInPool(/*items: [String],*/ snapshot: DataSnapshot, completion: @escaping (_ success: Bool) -> Void) {
var items: [String] = []
for item in snapshot.children {
let user = (item as! DataSnapshot).key
self.userRef.child(user).child("username").observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value
items.append(username! as! String)
})
}
self.players = items
// ISSUE HERE THE PLAYER.COUNT IS ALWAYS ZERO (0)!!!!!!!!!
for j in 0 ..< players.count {
print(players[j]description)
}
completion(true)
}
问题在于播放器数组计数始终为零(0)!?所以我不确定我是否正确使用了完成处理程序?
答案 0 :(得分:1)
observeSingleEvent
调用从服务器加载数据,因此异步发生。这意味着您的items.append(username! as! String)
在呼叫completion(true)
之后运行。
获得所需行为的一种简单方法是使用一个简单的计数器检查是否已加载所有用户名:
func loadPlayersInPool(/*items: [String],*/ snapshot: DataSnapshot, completion: @escaping (_ success: Bool) -> Void) {
var items: [String] = []
let loadedCount = 0
for item in snapshot.children {
let user = (item as! DataSnapshot).key
self.userRef.child(user).child("username").observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value
items.append(username! as! String)
loadedCount++
if loadedCount == snapshot.childrenCount {
self.players = items
for j in 0 ..< players.count {
print(players[j]description)
}
completion(true)
}
})
}
}