如何在swift ios中通过键值读取子数据或过滤firebase数据
Posted
技术标签:
【中文标题】如何在swift ios中通过键值读取子数据或过滤firebase数据【英文标题】:How to read child or filter firebase data by its key value in swift ios 【发布时间】:2015-08-03 16:20:53 【问题描述】:我是 swift 和 firebase 的新手,我正在尝试使用下面的代码打印所有商品和价格,我希望能够打印 ..
输出:
红椅100 沙发床120 var ref = Firebase(url: "https://jeanniefirstapp.firebaseio.com")
var item1 = ["name": "Alan Turning", "item" : "Red Chair", "price": "100"]
var item2 = ["name": "Grace Hopper", "item": "Sofa Bed" , "price": "120"]
var item3 = ["name": "James Cook" , "item": "White Desk", "price": "250"]
var item4 = ["name": "James Cook" , "item": "Mattress Cal King", "price": "100"]
override func viewDidLoad()
super.viewDidLoad()
var usersRef = ref.childByAppendingPath("users")
var users = ["item1": item1, "item2": item2, "item3" : item3 , "item4" : item4 ]
usersRef.setValue(users)
ref.queryOrderedByChild("price").observeEventType(.Value, withBlock: snapshot in
if let price = snapshot.value["price"] as? Int
println("\(snapshot.key) price at \(price) Dollars ")
println(snapshot.key)
)
【问题讨论】:
【参考方案1】:由于您想为每个项目执行相同的代码,您需要使用.ChildAdded
:
ref.queryOrderedByChild("price").observeEventType(.ChildAdded, withBlock: snapshot in
if let price = snapshot.value["price"] as? Int
println("\(snapshot.key) price at \(price) Dollars ")
println(snapshot.key)
)
有关更多信息和示例,请参阅page on retrieving data in the Firebase guide for ios developers。
更新
我最终在本地 xcode 中使用了您的代码,发现有两个问题。所以这三个结合起来:
您正在侦听.Value
事件,但您的块一次只处理一个项目。解决方案:
ref.queryOrderedByChild("price")
.observeEventType(.ChildAdded, withBlock: snapshot in
您正在***监听.Value
事件,但您正在添加users
下的项目。解决方案:
ref.childByAppendingPath("users")
.queryOrderedByChild("price")
.observeEventType(.ChildAdded, withBlock: snapshot in
您正在测试价格是否为Int
,但正在将它们添加为字符串。解决方案:
var item1 = ["name": "Alan Turning", "item" : "Red Chair", "price": 100]
var item2 = ["name": "Grace Hopper", "item": "Sofa Bed" , "price": 120]
var item3 = ["name": "James Cook" , "item": "White Desk", "price": 250]
var item4 = ["name": "James Cook" , "item": "Mattress Cal King", "price": 100]
通过这些更改,代码会为我打印出这些结果:
item1 price at 100 Dollars
item1
item4 price at 100 Dollars
item4
item2 price at 120 Dollars
item2
item3 price at 250 Dollars
item3
【讨论】:
嗨,我试过了,但我找不到它返回以上是关于如何在swift ios中通过键值读取子数据或过滤firebase数据的主要内容,如果未能解决你的问题,请参考以下文章