从Firebase打印数据
这是我的代码:
@IBAction func submitAnswer(_ sender: Any) {
getData()
print(array)
}
func getData() {
let ref = Database.database().reference().child("hobbies")
let query = ref.queryOrdered(byChild: "cost").queryEqual(toValue: "low" )
query.observe(.childAdded, with: { snapshot in
let hobbyName = snapshot.childSnapshot(forPath: "hobbyName").value as? String
self.array.append(hobbyName!)
})
{ error in
print(error)
}
}
这里的想法是,当我按下提交"按钮时,控制台将打印出Firebase中的数据.启动应用程序后,当我按它时,控制台将打印一个空数组.当我再次按下它时,控制台会打印出我想要的结果.我想让它在第一次尝试中打印出正确的结果.我该怎么办?
The idea here is that when I press the submit button, console will print out data from Firebase. After launching the app, when I press it, the console print an empty array. when I press it again, the console printed the result I wanted. I want to make it print the correct result on the 1st try. How do I do this ?
您正在打印数据源,在您的情况下,它是Firebase调用完成之前的self.array
.您需要做的是:
You are printing your datasource, in your case, it's the self.array
before your Firebase call completes. What you need to do is either:
-
在完成块内打印数据,如下所示:
Print your data inside the completion block, like so:
@IBAction func submitAnswer(_ sender: Any) {
getData()
}
func getData() {
let ref = Database.database().reference().child("hobbies")
let query = ref.queryOrdered(byChild: "cost").queryEqual(toValue: "low" )
query.observe(.childAdded, with: {( snapshot) in
self.array.append((snapshot.childSnapshot(forPath: "hobbyName").value as? String)!)
print(array) // Print inside this block instead :)
}) { (error) in
print(error)
}
}
或者,如果您真的想在submitAnswer
函数中打印数据,那么您将需要在getData()
函数中添加一个完成块,就像这样.
Or if you really want to print your data inside your submitAnswer
function, then you would need a completion block in your getData()
function, like so.
@IBAction func submitAnswer(_ sender: Any) {
getData {
// Completed! Now you can print your updated data from your datasource.
print(array)
}
}
func getData(withBlock completion: @escaping () -> Void) {
let ref = Database.database().reference().child("hobbies")
let query = ref.queryOrdered(byChild: "cost").queryEqual(toValue: "low" )
query.observe(.childAdded, with: {( snapshot) in
self.array.append((snapshot.childSnapshot(forPath: "hobbyName").value as? String)!)
completion()
}) { (error) in
print(error)
}
}
让我知道这是否有帮助.
Let me know if this helps.