JPC
JPC

Reputation: 5183

How to read child or filter firebase data by its key value in swift ios

I'm new to both swift and firebase , I'm trying to get all the item and price printed using this code below , I want to be able to print ..

output :

enter image description here

  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)
    }
})

Upvotes: 0

Views: 12074

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599956

Since you want to execute the same code for each item, you'll want to use .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)
  }
})

See the page on retrieving data in the Firebase guide for iOS developers for more information and examples.

Update

I ended up using your code in a local xcode and see there are two problems. So all three combined:

  1. you are listening for the .Value event, but your block is dealing with a single item at a time. Solution:

    ref.queryOrderedByChild("price")
       .observeEventType(.ChildAdded, withBlock: { snapshot in
    
  2. you are listening for the .Value event at the top-level, but you are adding the items under users. Solution:

    ref.childByAppendingPath("users")
       .queryOrderedByChild("price")
       .observeEventType(.ChildAdded, withBlock: { snapshot in
    
  3. you are testing whether the price is an Int, but are adding them as strings. Solution:

    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]
    

With those changes, the code prints out these results for me:

item1 price at 100 Dollars 
item1
item4 price at 100 Dollars 
item4
item2 price at 120 Dollars 
item2
item3 price at 250 Dollars 
item3

Upvotes: 8

Related Questions