Alex. E
Alex. E

Reputation: 79

Filtering data snapshot Swift Firebase

I'm trying to return data from the database which I've done successfully. The problem is I don't want all data to be featured, but only the ones with the current UID which is stored in the JSON tree.

Here is my JSON tree, there is only one current UID but there will be many.

user_posts- 
  LDLc60j71FBvJGeYn5i 
     description: "Write here"
     photoUrl: "https://firebasestorage.googleapis.com/v0/b/blo..."
     uid: "zQRxvM3cwzQMewUtVamk8JQrEFJ3"

Here is my current code returning all data from database folder:

var posts2 = [user_posts]()
func loadPosts(){
    Database.database().reference().child("user_posts").observe(.childAdded) {(snapshot: DataSnapshot) in
        if let dict = snapshot.value as? [String: Any] {
            let descriptionText = dict["description"] as! String
            let photoUrlString = dict["photoUrl"] as! String
            let post = user_posts(descriptionText: descriptionText, photoUrlString: photoUrlString)
            self.posts2.append(post)
            self.myPageTableView.reloadData()
        }
    }
}


override func viewDidLoad() {
    super.viewDidLoad()
    self.hideKeyboardWhenTappedAround()
    myPageTableView.dataSource = self
    myPageTableView.delegate = self
    loadPosts()

}



func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return posts2.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier:"myPageCell", for: indexPath)
        as! myPageTableViewCell
    cell.myPageDescription?.text = posts2[indexPath.row].description
    let photoUrl = posts2[indexPath.row].photoUrl
    let url = URL(string: photoUrl)
    cell.myPageImage.sd_setImage(with: url, placeholderImage: nil)
    return cell
    }
}

Upvotes: 0

Views: 599

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598623

To load only the posts for a specific user, you'll want to use a Firebase query:

let uid = Auth.auth().currentUser.uid
let posts = Database.database().reference().child("user_posts")
let query = posts.queryOrdered(byChild: "").queryEqual(toValue: uid)
query.observe(.childAdded) {(snapshot: DataSnapshot) in
  ...

Also see the Firebase documentation on ordering and filtering data.

Upvotes: 1

Related Questions