0

I want to get the post for only the postkeys that are in the array. I have tried with the code below and some variations of it, but it doesn't work. Does anyone know how to do this?

func fetchData(){

    DataService.ds.REF_POSTS.queryEqual(toValue: postKeys[IndexPath]).observeSingleEvent(of: .value, with: { (snapshot) in
        if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
            for snap in snapshot {
                print("SNAP: \(snap)")
                if let postDict = snap.value as? Dictionary<String, Any>{
                    let key = snap.key
                    let post = Post.init(postKey: key, postData: postDict)
                    self.posts.append(post)
                    print("USERPST: \(self.posts)")
                }
            }
        }
        self.posts.reverse()
        self.tableView.reloadData()
    })
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • What is the value of `postKeys[IndexPath]`? Can you reproduce the problem when you replace that with a hardcoded value? – Frank van Puffelen Nov 24 '17 at 01:18
  • The value of postKeys[IndexPath] is Array of Strings (it contains post keys). It doesn't work with a hardcoded array, but It works fine getting all the post from DataService.ds.REF_POSTS. The problem here is that I only want specific posts from the spesific keys in the array. – user1234567890 Nov 24 '17 at 08:18
  • There is no way to pass a list of IDs to Firebase and retrieve the items for those IDs. See https://stackoverflow.com/questions/29560088/firebase-equivalent-to-sql-where-in – Frank van Puffelen Nov 24 '17 at 16:18

1 Answers1

0

My code was a bit off. I figured it out:

    func fetchData(){
    DataService.ds.REF_POSTS.observeSingleEvent(of: .value, with: { (snapshot) in
        for key in self.postKeys{
            if let postDict = snapshot.childSnapshot(forPath: key).value as? Dictionary<String, Any>{
                print("SNAP: \(postDict)")
                    let post = Post.init(postKey: key, postData: postDict)
                    self.posts.append(post)
                }
        self.posts.reverse()
        self.tableView.reloadData()
        }
    })

}
  • This code downloads **all data** under `REF_POSTS` and then filters client-side. This uses more bandwidth than needed. – Frank van Puffelen Nov 24 '17 at 16:17
  • Do you have any suggestions? – user1234567890 Nov 25 '17 at 15:40
  • If all IDs are in a range, you can use a range filter (i.e. `queryStartingAtValue()` and `queryEndingAtValue()`). But more likely, you'll need to load each item separately. While code intensive, that is not as slow as you may think because Firebase pipelines the requests. See http://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786 – Frank van Puffelen Nov 25 '17 at 15:51