Duplicate collectionView cells after reloadData with Firebase query

谁都会走 提交于 2021-02-13 17:29:31

问题


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 Firebase Firestore collection but they get duplicated for a total of 9 cells.

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()
                }
            }
        }
    }
}

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?

Thanks!!

EDIT 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)])
        }
    }
}

回答1:


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




回答2:


You must clear the array holding your objects after

collectionView?.refreshControl?.beginRefreshing()
self.messages = []

And then call

self.collectionView?.reloadData()

Otherwise, you'll get the "Index out of Range" Error



来源:https://stackoverflow.com/questions/54740003/duplicate-collectionview-cells-after-reloaddata-with-firebase-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!