【问题标题】:Filtering data snapshot Swift Firebase过滤数据快照 Swift Firebase
【发布时间】:2018-05-28 23:36:19
【问题描述】:

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

【问题讨论】:

    标签: swift firebase firebase-realtime-database


    【解决方案1】:

    要仅加载特定用户的帖子,您需要使用 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

    【讨论】:

      猜你喜欢
      • 2017-01-30
      • 1970-01-01
      • 2017-01-30
      • 2023-02-11
      • 1970-01-01
      • 2017-11-17
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      相关资源
      最近更新 更多