我对Firebase还是个新手,对Swift也很新,所以请原谅任何不正确的语法。我在读取Firebase中多个子节点下的数据时遇到一些麻烦,当在一个子节点下时显示数据,但是当我尝试将其定位在两个子节点下时,在基本上相同的条件下显示为nil。
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()
on 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"]
返回nil
,即使在子节点上使用类似的代码返回实际的字符串也是如此。请让我知道是否有任何可能会丢失的东西,但是我尝试了很多,却没有获得理想的结果。
答案 0 :(得分:1)
看看您的结构,其中包含各种值
"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)