gpt4 book ai didi

ios - 从 Firebase 打印数据

转载 作者:行者123 更新时间:2023-11-30 12:04:56 24 4
gpt4 key购买 nike

这是我的代码:

@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 打印出数据。启动应用程序后,当我按下它时,控制台会打印一个空数组。当我再次按下它时,控制台打印出我想要的结果。我想让它在第一次尝试时打印出正确的结果。我该怎么做?

最佳答案

您正在打印数据源,在您的例子中,它是 Firebase 调用完成之前的 self.array。您需要做的是:

  1. 在完成 block 中打印数据,如下所示:

    @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)

    }
    }
  2. 或者,如果您确实想在 submitAnswer 函数中打印数据,那么您需要在 getData() 函数中添加一个完成 block ,如下所示.

    @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)

    }
    }

请告诉我这是否有帮助。

关于ios - 从 Firebase 打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46783231/

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