我正在寻找键的数量,然后从Firebase中先前设置的数据列表中获取键值。我正在尝试完全理解完成处理程序,但是我可能还不在那里。为什么返回一个空数组?还是至少在下一个函数(此代码之外)运行之前不填充数据?谢谢!
//Initial data download from Firebase
func getKeys(completion: @escaping () -> Void) {
Database.database().reference().child("food").observe(.value) { (snapshot) in
//Get count of how many child "apples"
Let childApplesCount = Int(snapshot.childrenCount)
//Get each key
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
print("keys in snapshot: \(key)")
//Append to an array of keys for later use
self.onloadKeyArray.append(key)
}
}
completion()
}
答案 0 :(得分:1)
现在,完成调用在数据库调用的闭包之外,因此在返回数据之前立即调用它。如果将其移至闭包中,则可以在需要时访问该信息。 blog post I wrote可以帮助您更好地了解处理闭包。
func getKeys(completion: @escaping () -> Void) {
Database.database().reference().child("food").observe(.value) { (snapshot) in
//Get count of how many child "apples"
Let childApplesCount = Int(snapshot.childrenCount)
//Get each key
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
print("keys in snapshot: \(key)")
//Append to an array of keys for later use
self.onloadKeyArray.append(key)
}
completion()
}
}
此外,如果您需要在闭包之外使用此数据,则最好将其传递给完成处理程序,如下所示:
func getKeys(completion: @escaping ([String]) -> Void) {
keyArray = [String]()
Database.database().reference().child("food").observe(.value) { (snapshot) in
//Get count of how many child "apples"
Let childApplesCount = Int(snapshot.childrenCount)
//Get each key
for child in snapshot.children {
let snap = child as! DataSnapshot
let key = snap.key
print("keys in snapshot: \(key)")
//Append to an array of keys for later use
keyArray.append(key)
}
completion(keyArray)
}
}
然后,当您调用函数时,将获得数组。这使您能够将数据功能与视图控制器分开。
yourClass.getKeys() { keyArray in
self.keys = keyArray
}