【问题标题】:Firebase swift not retrieving all child valuesFirebase swift没有检索所有子值
【发布时间】:2019-07-18 02:14:30
【问题描述】:

我在我的 Swift 构建的 iOS 应用程序中有一段代码,用于从 Firebase 实时数据库中检索所有节点。当我执行下面的代码时,我注意到它没有返回所有子节点。

当我查询未单独返回的特定节点时,首先代码返回“nil”,然后第二次尝试检索节点。 (在此过程中不做任何代码更改)。在此过程之后,节点开始显示在结果中,并带有检索所有节点功能。

示例 1:首先返回 nil,然后第二次尝试返回节点。我可以从控制台看到,并且肯定存在于数据库中。

ref?.child("transactions").child(email).child("14526452327").observeSingleEvent(of: .value, with: { (snapshot) in
                // Get user value
                let value = snapshot.value as? NSDictionary
                        print(value)
                        print("!!****************!!")
                // ...
            }) { (error) in
                print(error.localizedDescription)
            }

以下内容用于检索所有子值;起初这并没有得到所有节点,但是在运行示例 1 中的代码(两次)后,它开始返回有问题的节点。

ref?.child("transactions").child(email).observeSingleEvent(of: .value, with: { (snapshot) in

        let childrenCount = snapshot.childrenCount
        var counter : Int = 0

        for trans in snapshot.children.allObjects as! [DataSnapshot]
        {
            counter = counter + 1

            self.ref?.child("transactions").child(email).child(trans.key).observeSingleEvent(of: .value, with: { (snapshot2) in

我还检查了我的 Firebase 查询和数据限制,但我离免费帐户的门槛还差得很远。任何帮助是极大的赞赏。

【问题讨论】:

  • 你能用代码更清楚地描述你的问题吗?当你说on a second attempt returns the node时,你是什么意思?你的意思是重新启动你的应用程序并打印节点?
  • 您好@JIEWANG,感谢您的回复。我只是用上面提供的代码重新运行应用程序。我没有做任何更改...
  • 检查您的电子邮件变量是否始终具有正确的值,
  • 您是否启用了离线持久性?
  • 这听起来像是一个简单的调试场景: 1. 正如 shahzaib 所提到的,您的电子邮件是创建 url 路径的唯一变量,打印出来以确保它是正确的(例如,如果电子邮件是尚未设置)。 2. 你的控制台日志说什么,firebase 通常会给出很好的错误信息。 3. 与第 1 点类似,在执行“observesingleevent”之前单步执行您的代码并确保您打算初始化的所有内容都已完成。

标签: swift firebase firebase-realtime-database


【解决方案1】:

试试这个:

func getData() {
    // Making a reference
    let transactionRef = Database.database().reference(withPath: "transactions")
    transactionRef.observeSingleEvent(of: .value, with: { (snapshot) in

        // Printing the child count
        print("There are \(snapshot.childrenCount) children found")    

        // Checking if the reference has some values
        if snapshot.childrenCount > 0 {

            // Go through every child
            for data in snapshot.children.allObjects as! [DataSnapshot] {
                if let data = data.value as? [String: Any] {

                    // Retrieve the data per child


                    // Example
                    let name = data["name"] as? String
                    let age = data["age"] as? Int

                    // Print the values for each child or do whatever you want
                    print("Name: \(name)\nAge: \(age)")
                }
            }
        }
    })
}

【讨论】:

  • 请解释你的答案 - 回顾
猜你喜欢
  • 2017-07-13
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
  • 2017-05-09
  • 1970-01-01
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
相关资源
最近更新 更多