首页 > 解决方案 > 读取多个子节点时遇到问题(Firebase)

问题描述

我对 Firebase 很陌生,对 Swift 也很陌生,所以请原谅任何不正确的语法。我在读取 Firebase 中多个子节点下的数据时遇到了一些问题,当我尝试在两个子节点下定位数据时,数据显示在一个子节点下但在基本相同的条件下为零。

adminClientHandle = ref.child("Test").child("client1").observe(.value, with : { (snapshot) in
            let adminClientStuff = snapshot.value as? [String:String]

            //Goals
            if adminClientStuff?["Goal 1"] != nil {
                self.adminGoal1.text = adminClientStuff?["Goal 1"]
            } else {
                self.adminGoal1.text = "nil"
            }

ref = Database.database().reference()viewDidLoad

当firebase数据库看起来像这样时:

{
  "Test" : {
    "client1" : {
      "Goal 1" : "Goal 1",
      "Goal 1 %" : "100",
      "Goal 1 Correct" : 1,
      "Goal 1 Total" : "1",
      "Goal 2" : "Will keep personal space for 10 minutes",
      "Goal 2 %" : "0",
      "Goal 2 Correct" : 1,
      "Goal 2 Total" : "1",
      "Goal 3" : "Will recall events that happened in the last hour",
      "Goal 3 %" : "0",
      "Goal 3 Correct" : 1,
      "Goal 3 Total" : "1"
    }
  }
}

adminClientStuff?["Goal 1"]nilreturn ,即使带有 on 子节点的类似代码返回一个实际的字符串。请让我知道是否有任何我可能遗漏的东西,但我已经尝试了很多但没有达到预期的结果。

标签: swiftfirebasefirebase-realtime-database

解决方案


查看您的结构,其中包含多种值

  "Goal 1" : "Goal 1",
  "Goal 1 %" : "100",
  "Goal 1 Correct" : 1,

所以这不起作用,因为它是一个异构集合文字问题

let adminClientStuff = snapshot.value as? [String:String]

它需要像这样定义

let adminClientStuff = snapshot.value as? [String:Any]

我还建议使用不同的解决方案来保护您的代码,以防某个值丢失或不是预期的值。

let goal1 = snapshot.childSnapshot(forPath: "Goal 1").value as? String ?? "No Goal value"
let goal1Percent = snapshot.childSnapshot(forPath: "Goal 1 %").value as? String ?? "No Goal value"
let goal1Correct = snapshot.childSnapshot(forPath: "Goal 1 Correct").value as? Int ?? 0
print(goal1, goal1Percent, goal1Correct)

推荐阅读