Swift 检索 Firebase 数据 [英] Swift Retreive Firebase data
本文介绍了Swift 检索 Firebase 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Firebase 数据库中的以下数据:
The following data in the Firebase Database:
{
"schedule": {
"Week 1": {
"active": "true"
},
"Week 2": {
"active": "true"
},
"Week 3": {
"active": "false"
},
"Week 4": {
"active": "true"
},
...
}
}
我想检索只有 active 为 true 的所有周.我正在设置 Firebase 参考:
I want to retrieve all the Weeks where the active is true only. I am setting the Firebase reference as such:
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 需要加载到字符串类型数组中的几周:
Can someone please suggest how I can get just the weeks where active is set to true which needs to be loaded in an array of type string :
var weeksActive = [String]()
推荐答案
为此,您可以像这样使用 queryOrdered(byChild:)
和 queryEqual(toValue:)
.
For that you can use queryOrdered(byChild:)
and queryEqual(toValue:)
like this.
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)")
}
})
这篇关于Swift 检索 Firebase 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文