SwiftUI - 新评论在发布时重复

时间:2021-07-12 21:31:30

标签: ios firebase google-cloud-firestore swiftui

在我的评论功能中,我已经做到了每个帖子都有自己的评论集,每次按下“评论”按钮时,评论都必须重新加载,因此其他帖子的评论不会继续。

>

但是,当我发布新评论时,视图会复制评论。但是当我重新加载评论视图时,重复的评论减少到一个,这就是它应该的方式。 Firebase 中仅创建了一个评论文档,因此重复问题出在我的应用中,而不是 Firebase。

我已经在这里演示了这一点,因为我认为这是显示问题的最佳方式:https://giphy.com/gifs/ZpYBXPnhcjlAz33Hb9

在此 GIF 中,您将看到新评论创建了自己的 5 个版本。然后,当我关闭视图并重新加载它时,相同的评论只显示一个实例,这正是我想要的。

不确定如何解决这个问题。我曾想过在发表评论时完全关闭并重新打开视图,但我认为这不是最有效的处理方式。

CommentsView.swift

@ObservedObject var commentsData: CommentsViewModel
 HStack(){
                TextField("Type Something...", text: $commentsData.commentTxt)
                    .foregroundColor(.white)
                    .frame(height: 40)
                    .textFieldStyle(PlainTextFieldStyle())
                    .background(Color.white.opacity(0.06))
                    .multilineTextAlignment(.center)
                    .cornerRadius(12)

                Button(action: {
                        commentsData.comment(id: post.id)
                        commentsData.commentTxt = ""}) {
                    Text("Comment")
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                        .padding(.vertical,5)
                        .padding(.horizontal,15)
                        .background(Color("blue"))
                        .clipShape(Capsule())
                }
            }
            .padding()
            .background(Color.white.opacity(0.06))
            .cornerRadius(5)
            .preferredColorScheme(.dark)

if commentsData.comments.isEmpty{
                
                Spacer(minLength: 0)
                
                if commentsData.noComments{
                    Text("No Comments")
                    
                }
                else{
                    ProgressView()
                }
                Spacer(minLength: 0)
            }
            else{
                ScrollView{
                    VStack(spacing: 15){
                        
                        ForEach(commentsData.comments){comment in
                            
                            CommentsRow(post: post, comment: comment, commentData: commentsData)
                            
                        }
                    }
                    .padding()
                    .padding(.bottom,55)
                }
            }
            
            
        }
        .onAppear {
          commentsData.post = post
        }

CommentsViewModel.swift

class CommentsViewModel : ObservableObject{
    
    @Published var comments: [CommentsModel] = []
    @Published var noComments = false
    @Published var newComment = false
    @Published var commentTxt = ""

    let ref = Firestore.firestore()
    let uid = Auth.auth().currentUser!.uid

    var post: PostModel? {
        didSet{
            if let post = self.post {
                getComments(id: post.id)
            }
        }
    }

    func getComments(id: String) {
        print("ID from getComments is: \(id)")
        ref.collection("Posts").document(id).collection("Comments").addSnapshotListener { (snap, err) in
            
        guard let docs = snap else{
            self.noComments = true
            return
            }
            
            if docs.documentChanges.isEmpty{
                self.noComments = true
                return
            }
            
            docs.documentChanges.forEach { (doc) in
                
                //Checking if doc added
                
                if doc.type == .added{
                    
                    let title = doc.document.data()["title"] as! String
                    let time = doc.document.data()["time"] as! Timestamp
                    let userRef = doc.document.data()["ref"] as! DocumentReference
                    
                fetchUser(uid: userRef.documentID) { (user) in
                    
                    self.comments.append(CommentsModel(id: doc.document.documentID, title: title, time: time.dateValue(), user: user))
                    
                    self.comments.sort { (p1, p2) -> Bool in
                        return p1.time > p2.time
                        
                    }
                }
            }
            
                if doc.type == .removed{
                    
                    let id = doc.document.documentID
                    
                    self.comments.removeAll { (comment) -> Bool in
                        return comment.id == id
                    }
                }
                
                if doc.type == .modified{
                    
                    print("Updated...")
                    
                    let id = doc.document.documentID
                    let title = doc.document.data()["title"] as! String
                    
                    let index = self.comments.firstIndex { (comment) -> Bool in
                        return comment.id == id
                    } ?? -1
                    
                    if index != -1{
                        self.comments[index].title = title
                    }
                }
        }
    }
}
func comment(id: String){
        //posting data
            
            let newDocRef = ref.collection("Posts").document(id).collection("Comments").document()
            newDocRef.setData([
                "title" : self.commentTxt,
                "ref": ref.collection("Users").document(self.uid),
                "time": Date(),
            ]){ (err) in
                
                if err != nil{
                    return
                }
            }
    }
}

PostRow.swift

var commentsData = CommentsViewModel()
@State private var showingComments = false
Button(action: {
                    commentsData.comments.removeAll()
                    showingComments = true
                }){
                    Text("Comments")
                }
                .transition(.move(edge: .leading))
                .sheet(isPresented: self.$showingComments)
                {
                    CommentsView(commentsData: commentsData, post: post)
                }

CommentsModel.swift / PostModel.swift

struct CommentsModel : Identifiable {
    var id: String
    var title: String
    var time: Date
    var user: UserModel
}
struct PostModel : Identifiable {
    
    var id: String
    //other vars unrelated to this
}

如果需要更多代码,请告诉我,我会提供。任何帮助/建议都会有所帮助。

编辑:还没有弄清楚这一点。如果有人知道,请告诉我!

0 个答案:

没有答案
相关问题