我是swift和firebase的新手,我正在尝试使用下面的代码打印所有项目和价格,我希望能够打印..
输出:
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)
}
})
答案 0 :(得分:8)
由于您要为每个项目执行相同的代码,因此您需要使用.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