【问题标题】:swift3 append function does not work inside of firebase observeSingleEventswift3 append 功能在 firebase observeSingleEvent 内不起作用
【发布时间】:2017-04-04 05:28:06
【问题描述】:

我正在尝试使用观察者从 firebase 获取数据。但是当我尝试将值附加到我之前创建的数组中时,它失败了。这是代码,有人可以帮我吗?

class ProductTableViewController: UITableViewController{
    var productName:[String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        fetchProduct()
        print(self.productName.count)
    }

    func fetchProduct(){
        let currentUserId = FIRAuth.auth()?.currentUser?.uid

        FIRDatabase.database().reference().child("users").child(currentUserId!).child("products").observe(.value, with: { (snapshot) in
                self.productName.append("Hello")
        }, withCancel: nil)
    }

在我将一个值附加到该数组后它应该打印 1 但它打印 0。

【问题讨论】:

  • print 行和append 行上放置一个断点。现在运行您的代码并注意首先调用哪个代码。
  • 这是因为 Firebase 监听器是异步的。您应该能够在 Swift 中在线找到大量关于如何处理此问题的示例。

标签: ios arrays swift firebase firebase-realtime-database


【解决方案1】:

您必须知道 Firebase 观察者是异步的,因此即使您先调用它,它也必须等待响应。与此同时,您的应用程序将继续执行其余代码,因此它将调用打印函数。如果您想证明这一点,请尝试将 print 放入 firebase 调用中:

class ProductTableViewController: UITableViewController{
var productName:[String] = []

override func viewDidLoad() {
    super.viewDidLoad()
    fetchProduct()

}

func fetchProduct(){
    let currentUserId = FIRAuth.auth()?.currentUser?.uid

    FIRDatabase.database().reference().child("users").child(currentUserId!).child("products").observe(.value, with: { (snapshot) in
            self.productName.append("Hello")
            print(self.productName.count)
    }, withCancel: nil)
}

希望对你有帮助!

【讨论】:

  • 谢谢,真的很有帮助
猜你喜欢
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2018-11-19
  • 2018-10-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多