swift - 读取多个子节点时遇到问题(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"]
nil
return ,即使带有 on 子节点的类似代码返回一个实际的字符串。请让我知道是否有任何我可能遗漏的东西,但我已经尝试了很多但没有达到预期的结果。
解决方案
查看您的结构,其中包含多种值
"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)
推荐阅读
- bootstrap-4 - Align element on the right in
- reactjs - 创建反应应用程序 | 当浏览器连接到应用程序时,是否可以从后端提供文件而不是提供 index.html
- recommendation-engine - 如何建立零售银行产品推荐系统的训练集
- django - 如何将 mixpanel 集成到 django 后端
- .net - “GetFileHash”任务意外失败
- vba - VBA excel到Webform
- php - Laravel 8:调用路由时数组到字符串的转换:列表
- python - 如何仅在 Django 网页上的特定时间显示模型对象?
- vue.js - 更改 vuetify 扩展面板标题中扩展图标的颜色
- ios - 如何解决flutter中的iOS部署目标问题