【问题标题】:Efficiently determine if user liked post in Firebase有效地确定用户是否喜欢 Firebase 中的帖子
【发布时间】:2018-02-11 00:35:59
【问题描述】:

我有一个应用程序,用户可以在其中点赞帖子,我想确定当前用户之前是否以有效的方式点赞过帖子。我的数据目前如下所示:

我还存储每个用户的喜欢

在我当前的查询中,我正在这样做:

if let people = post["peopleWhoLike"] as? [String: AnyObject] {
      if people[(Auth.auth().currentUser?.uid)!] != nil {
           posst.userLiked = true
      }
}

但是,我认为这需要我下载所有帖子的点赞,效率不高,所以我尝试了这个:

 if (post["peopleWhoLike\(Auth.auth().currentUser!.uid)"] as? [String: AnyObject]) != nil {
     posst.userLiked = true
 }

第二种方法似乎无法正常工作。有一个更好的方法吗?

这也是我最初的查询:

pagingReference.child("posts").queryLimited(toLast: 5).observeSingleEvent(of: .value, with: { snap in
        for child in snap.children {
            let child = child as? DataSnapshot
            if let post = child?.value as? [String: AnyObject] {
                let posst = Post()
                if let author = post["author"] as? String, let pathToImage = post["pathToImage"] as? String, let postID = post["postID"] as? String, let postDescription = post["postDescription"] as? String, let timestamp = post["timestamp"] as? Double, let category = post["category"] as? String, let table = post["group"] as? String, let userID = post["userID"] as? String, let numberOfComments = post["numberOfComments"] as? Int, let region = post["region"] as? String, let numLikes = post["likes"] as? Int {

【问题讨论】:

  • 这被称为多对多关系,请查看:youtube.com/watch?v=HjlQH3RsGcU 在视频中间 Frank 将对此进行说明。 stackoverflow.com/questions/41527058/… 也许是你可以使用的东西。我认为您应该对数据库进行非规范化以更快地查询。是的,您通过这种方式获得重复数据。
  • 数据已经非规范化,因为类似的内容存储在帖子和 userActivity...

标签: ios swift firebase


【解决方案1】:

解决了:

在 tableView 中,我只是直接查询喜欢的值,然后确定要显示的按钮。

static func userLiked(postID: String, cell: BetterPostCell, indexPath: IndexPath) {
        // need to cache these results so we don't query more than once
        if newsfeedPosts[indexPath.row].userLiked == false {
            if let uid = Auth.auth().currentUser?.uid {
                likeRef.child("userActivity").child(uid).child("likes").child(postID).queryOrderedByKey().observeSingleEvent(of: .value, with: { snap in
                    if snap.exists() {
                        newsfeedPosts[indexPath.row].userLiked = true
                        cell.helpfulButton.isHidden = true
                        cell.notHelpfulButton.isHidden = false
                    }
                })
                likeRef.removeAllObservers()
            }
        }
    }

在我的 TableView 中调用:

DatabaseFunctions.userLiked(postID: newsfeedPosts[indexPath.row].postID, cell: cell, indexPath: indexPath)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多