Swift Retreive Firebase数据 [英] Swift Retreive Firebase data
问题描述
{
schedule:{
第2周:{
active:true
},
Week 2:{
active:true
},
Week 3:{
active:false
},
Week 4:{
active:true
},
...
}
}
I想要检索只有活动状态为真的所有星期。
我将Firebase参考设置为:
ref = FIRDatabase.database()。reference(withPath:附表)
然后执行以下操作:
print(Count:,snapshot.childrenCount)
for _ in snapshot.children {
print(\(snapshot.value))
}
})
产生以下输出:
可选({
Week 1= {
active = 1;
};
Week 2= {
active = 1; $ b $第3周= {
活动= 0;
};
第4周= {
活动= 1;
} ;
...
}
只是几个星期重新激活被设置为真正需要被加载到一个字符串类型的数组:
var weeksActive = [String]()
为此,您可以使用 queryOrdered(byChild:)
和 queryEqual(toValue:)
就像这样。
<$ p $ ():$ {code> let ref = FIRDatabase.database()。reference(withPath:Schedule)。queryOrdered(byChild:active)。queryEqual(toValue:true)
ref .observe(.value,在
$ b $ print(Count:,snapshot.childrenCount)中的{(快照)$为快照.children中的子
{
print( \\((孩子当! (FIRDataSnapshot.value))
//得到星期,你需要访问键
print(\((child as!FIRDataSnapshot).key))
}
})
The following data in the Firebase Database:
{
"schedule": {
"Week 1": {
"active": "true"
},
"Week 2": {
"active": "true"
},
"Week 3": {
"active": "false"
},
"Week 4": {
"active": "true"
},
...
}
}
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")
and then doing the following:
ref.observeSingleEvent(of: .value, with: { snapshot in
//
print("Count: ", snapshot.childrenCount)
for _ in snapshot.children {
print("\(snapshot.value)")
}
})
Which produces the following output:
Optional({
"Week 1" = {
active = 1;
};
"Week 2" = {
active = 1;
};
"Week 3" = {
active = 0;
};
"Week 4" = {
active = 1;
};
...
}
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]()
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 Retreive Firebase数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!