使用 Firebase 查询重新加载数据后重复 collectionView 单元格 [英] Duplicate collectionView cells after reloadData with Firebase query

查看:23
本文介绍了使用 Firebase 查询重新加载数据后重复 collectionView 单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Firebase 快照侦听器,用于检查新文档,将它们添加到数组(collectionView 数据源),然后重新加载 collectionView.但是,我在 collectionView 中得到了重复的单元格.我的 Firestore 集合中目前有 3 个对象,但它们被复制到总共 9 个单元格中.

I have a Firebase snapshot listener that checks for new documents, adds them to an array (the collectionView datasource), and then reloads the collectionView. However, I'm getting duplicate cells in the collectionView. I currently have 3 objects in my Firestore collection but they get duplicated for a total of 9 cells.

我什至添加了对索引的检查,因此 reloadData 仅在到达数组末尾后才会发生.相关代码如下:

I even added a check for the index so reloadData only happens after it reaches the end of the array. Here's the relevant code:

messageListener = query.addSnapshotListener { querySnapshot, error in
    guard let snapshot = querySnapshot else {
        print("Error listening for channel updates: (error?.localizedDescription ?? "No error")")
        return
    }
    
    snapshot.documentChanges.forEach { change in

        if change.type == .added {
            for document in snapshot.documents{
                
                 ....

                let newMessage = Message(sender: newSender, messageId: document.documentID, sentDate: date, text: text)
                
                self.messages.append(newMessage)
                
                guard let index = snapshot.documents.index(of: document) else {return}
                
                if index == (snapshot.documents.count - 1) {
                    self.messagesCollectionView.reloadData()
                }
            }
        }
    }
}

它正确地对索引进行倒计时,因此最终达到 2 == 2 以重新加载数据.但是,它然后又重新开始该过程两次,总共三个(3 个对象加载了三次,总共 9 个单元格).知道如何改进此逻辑流程以阻止重复吗?

It correctly counts down the index so it eventually reaches 2 == 2 to reloadData. However, it then starts the process over again two other times for a total of three (3 objects loaded three times for a total of 9 cells). Any idea how I can improve this logic flow to stop the duplicates?

谢谢!!

编辑 1

extension ChatViewController: MessagesDataSource {
    
    func currentSender() -> Sender {
        //guard let currentUserID = User.current?.key else {return nil}
        let newSender = Sender(id: (User.current?.key)!, displayName: (User.current?.username)!)
        return newSender
    }
    
        func numberOfSections(in messagesCollectionView: MessagesCollectionView) -> Int {
    return 1
}

func numberOfItems(inSection section: Int, in messagesCollectionView: MessagesCollectionView) -> Int {
    return messages.count
}
    func messageForItem(at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> MessageType {
        return messages[indexPath.section]
        
        func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
           
            return NSAttributedString(string: MessageKitDateFormatter.shared.string(from: message.sentDate), attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10), NSAttributedString.Key.foregroundColor: UIColor.darkGray])
        }
        
        func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
            let name = message.sender.displayName
            return NSAttributedString(string: name, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption1)])
        }
        
        func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
            
            let dateString = formatter.string(from: message.sentDate)
            return NSAttributedString(string: dateString, attributes: [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .caption2)])
        }
    }
}

推荐答案

messages 数组必须在重新填充快照文档之前重置.您可以在 for document in snapshot.documents

messages array must be reset before repopulate snapshot document. You can add self.messages.removeAll() before the line for document in snapshot.documents

这篇关于使用 Firebase 查询重新加载数据后重复 collectionView 单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆