gpt4 book ai didi

ios - 使用完成处理程序 IOS 从 Firebase 中的 child 获取初始键值

转载 作者:行者123 更新时间:2023-11-28 23:45:23 25 4
gpt4 key购买 nike

我想从 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()
}

最佳答案

现在,完成调用在数据库调用的闭包之外,因此它会在数据返回之前立即被调用。如果将其移入闭包中,您将能够在需要时访问信息。这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)
}
}

然后当您调用该函数时,您将获得数组。这使您能够将数据功能与 View Controller 分开。

yourClass.getKeys() { keyArray in
self.keys = keyArray
}

关于ios - 使用完成处理程序 IOS 从 Firebase 中的 child 获取初始键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52728576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com