Zaid Mustafa
Zaid Mustafa

Reputation: 211

How to make Firebase Database Query to get some of the children using Swift 3?

How can I make a Query in Firebase database to get some of the children in my console? For example, from the snapshot below, how can I make a query to get just the Images where Des: 11.

This is a snapshot for my console in firebase database

I'm using this code:

   func loadData(){


    Ref=FIRDatabase.database().reference().child("Posts")

    Handle = Ref?.queryOrdered(byChild: "11").observe(.childAdded ,with: { (snapshot) in

        if  let post = snapshot.value as? [String : AnyObject] {

            let img = Posts()

            img.setValuesForKeys(post)

            self.myarray.append(img)

                self.tableView.reloadData()

        }

    })

}

Upvotes: 3

Views: 3323

Answers (1)

Daniel Williams
Daniel Williams

Reputation: 266

As El Capitain said, you'll need to use this:

func loadData(){

    let ref = FIRDatabase.database().reference().child("Posts")

    ref?.queryOrdered(byChild: "Des").queryEqual(toValue: "11").observe(.childAdded, with: { snapshot in 
        if let post = snapshot.value as? [String : AnyObject] { 
            // do stuff with 'post' here.

        } 
    })

}

Also, as he mentioned, you'll want to set your security rules to allow you to search by 'Des', or whatever other child node you'll be querying by. In addition, you'll need to set the rules to allow you read access to the query location:

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null",

    "Posts": {
      "$someID": {
        ".indexOn": ["Des"]
      }
    }
  }
}

However, you're not going to get 'only the images' though, your query will return the entire node. In this case, the query above would return the rrrrrr node.

Upvotes: 4

Related Questions