从Firebase打印数据 [英] Print data from Firebase

查看:81
本文介绍了从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:

  1. 在完成块内打印数据,如下所示:

  1. 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.

    这篇关于从Firebase打印数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆