过滤Firebase数据Swift

时间:2016-11-10 08:23:00

标签: swift firebase firebase-realtime-database

我想用Swift在Firebase上加载Modern类型的每个图像。我该怎么做?

这是我的数据模型:

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

这是我尝试过的。但它没有用。

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

2 个答案:

答案 0 :(得分:1)

尝试: -

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

答案 1 :(得分:0)

  • 您的queryOrdered格式错误。另外,您总是将inserting中的一个对象self.posts放入 0索引,因此,您的数组中的对象总是替换为 0位置的对象。因此,您可以如下修改代码:

    self.posts = []
    DataBase.child("arts").queryOrdered(byChild: "type").queryEqual(toValue : "Modern").observe(.value) { (snapshot: FIRDataSnapshot) in
        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.append(post)           
                }
            }
            self.tableView.reloadData()               
        }
    }