kurbs kurbs - 25 days ago 17
Swift Question

Filter Firebase data Swift

I want to load every image of type Modern on Firebase with Swift. How can I do it?

Here's my data model:

"arts" : {
"-KW5plrmDFMGa9pUlTg3" : {
"description" : "Title ",
"height" : 25.36023,
"imageUrl" : "https://firebasestorage.googleapis.com/v0/b/medici-b6f69.appspot.com/o/Arts%2FJ7U039FN6YckdbQ7KgeJKuZDO2I3%2F26DDC192-C081-4588-BD52-2841FA3EF507?alt=media&token=e828936c-5341-4429-94e9-c3aefa81769b",
"postDate" : 1478657252917,
"title" : "Title ",
"type" : "Modern",
"width" : 25.99424
}


Here's what I tried. But it's not working.

DataBase.child("arts").queryOrdered(byChild: "Modern").observe(.value) { (snapshot: FIRDataSnapshot) in
self.posts = []

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
print("SNAPSHOT: \(snapshot)")

for snap in snapshot {
if let postDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key
let post = ProfileArtModel(key: key, artData: postDict)
self.posts.insert(post, at: 0)
}
}
}
self.tableView.reloadData()
}

Answer

Try:-

DataBase.child("arts").queryOrdered(byChild: "type").queryEqual(toValue : "Modern").observe(.value) { (snapshot: FIRDataSnapshot) in
self.posts = []

if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
    print("SNAPSHOT: \(snapshot)")

    for snap in snapshot {
        if let postDict = snap.value as? Dictionary<String, AnyObject> {
            let key = snap.key
            let post = ProfileArtModel(key: key, artData: postDict)
            self.posts.insert(post, at: 0)
            self.tableView.reloadData()
        }
    }
  }
}