Firebase数据库中的以下数据:
{ "schedule": { "Week 1": { "active": "true" }, "Week 2": { "active": "true" }, "Week 3": { "active": "false" }, "Week 4": { "active": "true" }, ... } }
我想检索所有仅活动为true的Weeks。我正在这样设置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的那几周需要加载到string类型的数组中:
var weeksActive = [String]()
为此,您可以使用queryOrdered(byChild:)并queryEqual(toValue:)喜欢这样。
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)") } })