我正在尝试从数据库中返回数据,我已成功完成。问题是我不希望显示所有数据,而只显示存储在 JSON 树中的具有当前 UID 的数据。
这是我的 JSON 树,当前只有一个 UID,但会有很多。
user_posts-
LDLc60j71FBvJGeYn5i
description: "Write here"
photoUrl: "https://firebasestorage.googleapis.com/v0/b/blo..."
uid: "zQRxvM3cwzQMewUtVamk8JQrEFJ3"
这是我当前从数据库文件夹返回所有数据的代码:
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
}
}
最佳答案
要仅加载特定用户的帖子,您需要使用 Firebase 查询:
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
...
关于swift - 过滤数据快照 Swift Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50564948/