Firebase 数据库中的以下数据:
{
"schedule": {
"Week 1": {
"active": "true"
},
"Week 2": {
"active": "true"
},
"Week 3": {
"active": "false"
},
"Week 4": {
"active": "true"
},
...
}
}
我想检索仅事件为 true 的所有周。 我将 Firebase 引用设置如下:
ref = FIRDatabase.database().reference(withPath: "Schedule")
然后执行以下操作:
ref.observeSingleEvent(of: .value, with: { snapshot in
//
print("Count: ", snapshot.childrenCount)
for _ in snapshot.children {
print("\(snapshot.value)")
}
})
产生以下输出:
Optional({
"Week 1" = {
active = 1;
};
"Week 2" = {
active = 1;
};
"Week 3" = {
active = 0;
};
"Week 4" = {
active = 1;
};
...
}
有人可以建议我如何获取 active 设置为 true 且需要加载到字符串类型数组中的周数吗:
var weeksActive = [String]()
最佳答案
为此,您可以像这样使用 queryOrdered(byChild:)
和 queryEqual(toValue:)
。
let ref = FIRDatabase.database().reference(withPath: "Schedule").queryOrdered(byChild: "active").queryEqual(toValue : true)
ref.observe(.value, with:{ (snapshot) in
print("Count: ", snapshot.childrenCount)
for child in snapshot.children {
print("\((child as! FIRDataSnapshot).value)")
//To get week you need to access key
print("\((child as! FIRDataSnapshot).key)")
}
})
关于ios - Swift 检索 Firebase 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719620/