【问题标题】:posts disappearing from feed when like button is pressed按下赞按钮时帖子从提要中消失
【发布时间】:2023-02-04 06:40:18
【问题描述】:

我正在使用以下功能更新我的提要中的帖子:

func fetchPosts() {
    let query = COLLECTION_POSTS
        .order(by: "timestamp", descending: true)

    query.addSnapshotListener { snapshot, _ in
        guard let changes = snapshot?.documentChanges.filter({$0.type == .added}) else {return}

        self.posts = changes.compactMap {
            do {
                return try $0.document.data(as: Post.self)
            } catch {
                print("Error converting Firestore document to Post object: \(error)")
                return nil
            }
        }
        self.fetchUserPosts()
    }
}

当我喜欢一个帖子并更新喜欢计数时,帖子从提要中消失,然后我通过 self.fetchuserposts() 函数收到一条调试消息,表明数据库中没有帖子。然而,尽管如此,服务器端的点赞量仍然在增加。

以下是在用户按下时更新 like 字段的代码:

func likePost(post: Post) {
    guard let uid  = Auth.auth().currentUser?.uid else { return }
    guard let postId = post.id else { return }
    let userLikesRef = Firestore.firestore().collection("users").document(uid).collection("user-likes")
        
    Firestore.firestore().collection("posts").document(postId)
        .updateData(["likes" : post.likes + 1]) { _ in
            userLikesRef.document(postId).setData([:]) { _ in
                self.isLiked = true
            }
        }
}

我尝试了许多不同的方法来更新 like 字段,但我似乎无法弄清楚。我预计可能存在模型未更新的问题,但考虑到快照侦听器正在侦听更改,这对我来说没有意义。

【问题讨论】:

    标签: swift firebase google-cloud-firestore state


    【解决方案1】:

    我(jankily)使用以下代码解决了这个问题。但是,当按下赞按钮时,提要中的所有帖子都会重新加载,这并不理想,如果有人有更好的解决方案,我仍然会很感激帮助!

    func fetchPosts() {

        let query = COLLECTION_POSTS
            .order(by: "timestamp", descending: true)
    
        query.addSnapshotListener { snapshot, _ in
            guard let changes = snapshot?.documentChanges else {return}
    
            for change in changes {
                
                if change.type == .added {
                    do {
                        let post = try change.document.data(as: Post.self)
                        self.postsArray.append(post)
                    } catch {
                        print("Error converting Firestore document to Post object: (error)")
                    }
                }
            }
            self.posts = self.postsArray
            self.fetchUserPosts()
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多