ios - 有效地确定用户是否喜欢 Firebase 中的帖子

标签 ios swift firebase

我有一个应用程序,用户可以在其中点赞帖子,我想确定当前用户之前是否以有效的方式点赞过帖子。我的数据目前看起来像这样:

Post Data

我还为每个用户存储了点赞数

User Likes

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

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 {

最佳答案

解决了:

在 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)

关于ios - 有效地确定用户是否喜欢 Firebase 中的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46008814/

相关文章:

ios - 两个 UIStackView 的约束 - 一个在另一个下面

firebase - Firebase-是否可以在Firebase Spark Plan中使用第三方服务提供商

firebase - angularfire $watch() 是一个属性,而不是整个对象? (火力底座,有角度)

ios - 为什么在函数外部引用不创建保留循环?

ios - 右侧带有部分索引的 SwiftUI 列表?

iOS 应用程序验证错误

ios - 使用 'YoutubePlayer Swift SDK' 在 tableviewCell 中播放 youtube 视频

ios - 无法将数据转换为字符周围的字符串

swift - 带字符串的 swift 类字典

android - 收到登录尝试的结果时,FirebaseAuthUI 使应用程序崩溃