swift - 过滤数据快照 Swift Firebase

标签 swift firebase firebase-realtime-database

我正在尝试从数据库中返回数据,我已成功完成。问题是我不希望显示所有数据,而只显示存储在 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
  ...

另见 Firebase documentation on ordering and filtering data .

关于swift - 过滤数据快照 Swift Firebase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50564948/

相关文章:

swift - 如何从 firebase 中删除帖子? swift

Firebase - 增加实时数据库限制

ios - Playground 执行失败 : error: Couldn't lookup symbols

ios - 从 JSON 图像 url swift 填充 collectionView

ios - 使用 ReachabilitySwift 时无法重新加载表

javascript - 使用 Firebase-GeoFire 获取用户附近的餐馆列表

ios - 检测到 Firebase 模式。应用程序包中的警告 : unable to find GoogleService-Info. plist,将不会上传 dSYM

android - 如何在 RecyclerView 上滑动删除?

android - com.google.firebase.database.DatabaseException

ios - 有没有办法禁用 UITableViewRowAction 按钮的辅助功能字体缩放?