【问题标题】:Firebase - sort posts by number of keys and show in TableViewFirebase - 按键数对帖子进行排序并显示在 TableView 中
【发布时间】:2018-01-28 20:19:39
【问题描述】:

我制作了一个应用程序,它使用 childByAutoID 键将用户消息及其用户名保存到 Firebase。里面有保存用户名、消息、喜欢和 PostID 的孩子(如下图所示)。

经过大量研究和大量尝试自己编写代码后,我发现喜欢需要在单独的子项中保存为 autoID 键,然后您必须计算这些键以获得喜欢的数量(您将看到那个孩子也在下面的图片上,那个孩子被命名为“喜欢”)

一切都显示在 tableView 单元格中。 但是所有这些都是随机显示的(我更愿意按添加日期排序),但真正想要的是在下一个 VC 中加载的数据显示为:

本周前 10 名 本月TOP 10 最好的等等......

菜单会有单独的按钮,当您按下它时,您将看到下一个包含具有相同数据的表视图的 VC,但这次按最喜欢的帖子排序。

这是将键写入 LIKED 子路径的代码(当在 Firebase 数据库中已加载的数据上按下 like 时):

    @IBAction func likePressed(_ sender: Any) {

    let ref = Database.database().reference()
    self.likeButton.isEnabled = false
    let key = ref.child("Frusters").childByAutoId().key

    ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

                let updateLikes = ["Liked/\(key)" : key] as [String : Any]
                    ref.child("Frusters").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in

                        if error == nil {
                            ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in
                        if let properties = snap.value as? [String : AnyObject] {
                        if let likes = properties["Liked"] as? [String : AnyObject] {

                        let count = likes.count
                        self.likeLabel.text = "\(count) Likes"

                        let update = ["likes" : count]
                        ref.child("Frusters").child(self.postID).updateChildValues(update)

                        self.likeButton.isHidden = true
                        self.unlikeButton.isHidden = false
                        self.likeButton.isEnabled = true
                        }
                    }
                })
            }
        })
    })

    ref.removeAllObservers()
}

这是加载数据并将其放在我的表格视图中的代码:

    func loadData() {
    self.fetchPosts.removeAll()
    let ref = Database.database().reference()
    ref.child("Frusters").observeSingleEvent(of: .value, with: { (snapshot) in
        if let postDict = snapshot.value as? [String:AnyObject] {
            for (_,postElement) in postDict {
                print(postElement);
                let post = Post()
                post.username = postElement["Username"] as? String
                post.message = postElement["Message"] as? String
                post.likes = postElement["likes"] as? Int
                post.postID = postElement["postID"] as? String
                self.fetchPosts.append(post)
            }
        }
        self.tableView.reloadData()

    }) { (error) in
        print(error.localizedDescription)
    }
    ref.removeAllObservers()
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")  as! PostTableViewCell

    cell.messageLabel.text = self.fetchPosts[indexPath.row].message
    cell.usernameLabel.text = self.fetchPosts[indexPath.row].username

    cell.likeLabel.text = "\(self.fetchPosts[indexPath.row].likes!) Likes"
    cell.postID = self.fetchPosts[indexPath.row].postID

    cell.bckgView.layer.cornerRadius = 0

    cell.bckgView.layer.shadowOffset = CGSize(width: 0, height: 1)
    cell.bckgView.layer.masksToBounds = false
    cell.bckgView.layer.shadowColor = UIColor.black.cgColor
    cell.bckgView.layer.shadowOpacity = 0.3
    cell.bckgView.layer.shadowRadius = 4

    return cell
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension;
}

好吧,问题是我不知道如何在我的新 UITableView 中插入最喜欢的前 10 个帖子,将它们从最喜欢的帖子排序到最喜欢的下 9 个帖子。

另外,是否可以对本月或本周最喜欢的它们进行排序? Firebase 数据库生成的这个键(通过 autoID)是否包含创建帖子的日期,或者我是否必须在其中插入带有日期的新子项,然后在代码中将“日期”子项和“喜欢的”子项组合为前 10 个喜欢的帖子之间本月的第一天和最后一天?

提前致谢。 ;)

【问题讨论】:

  • 对于本月前 10 名和本周前 10 名,您需要为该帖子添加 CreationDate 并按喜欢(点赞数)排序。
  • 我正在阅读 Firebase 文档并且有一些解释,但对我来说还不够。 :/ 在这里寻找答案,找到带有服务器时间戳的东西,但我还在学习,我不是那种自己编码的专家。我会尝试寻找其他东西并尝试使用我到目前为止找到的代码。感谢您回答我的问题@NishantBhindi
  • 也许在我里面 loadData() 我应该插入: let postOrderMostLikes = ref.child("Frusters").child(self.postID).queryOrdered(byChild: "likes") ?也许这会按喜欢的数量对我所有的帖子进行排序?
  • 这太令人沮丧了。我每天都在寻找答案,尝试了很多代码,现在我正式放弃了。我没有办法做到这一点。我要试试别的。

标签: ios uitableview firebase swift3 firebase-realtime-database


【解决方案1】:

1-如果您只关心数字,则不必单独存储每个类似的东西。您只需更新号码即可。

    @IBAction func likePressed(_ sender: Any) {

    let ref = Database.database().reference()
    self.likeButton.isEnabled = false
    let key = ref.child("Frusters").childByAutoId().key

    ref.child("Frusters").child(self.postID).observeSingleEvent(of: .value, with: { (snapshot) in

    let counted = snapshot.value as? Int
    self.ref.child("Flusters".child(self.postID).child("likes").setValue(counted! + 1)
})

2- 是的,您可以按喜欢排序。您需要使用 .queryOrdered 函数。更新代码如下

func loadData() {
    self.fetchPosts.removeAll()
    let ref = Database.database().reference()
    ref.child("Frusters").queryOrdered(byChild: "likes").observeSingleEvent(of: .value, with: { (snapshot) in
        if let postDict = snapshot.value as? [String:AnyObject] {
            for (_,postElement) in postDict {
                print(postElement);
                let post = Post()
                post.username = postElement["Username"] as? String
                post.message = postElement["Message"] as? String
                post.likes = postElement["likes"] as? Int
                post.postID = postElement["postID"] as? String
                self.fetchPosts.append(post)
            }
        }
        self.tableView.reloadData()

3- 要按周、月排序,您必须跟踪时间戳。

【讨论】:

    猜你喜欢
    • 2020-06-09
    • 2017-08-10
    • 1970-01-01
    • 2018-01-12
    • 2014-08-15
    • 1970-01-01
    • 2021-10-05
    • 2014-03-20
    • 1970-01-01
    相关资源
    最近更新 更多