使用Firebase查询在reloadData之后复制collectionView单元格

时间:2019-02-18 03:15:17

标签: ios swift firebase google-cloud-firestore messagekit

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

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

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

它正确地递减索引,因此最终reloadData达到2 == 2。但是,然后又重新启动了该过程,总共进行了两次(共三个)(3个对象加载了3次,共9个单元)。知道如何改善这种逻辑流程以阻止重复吗?

谢谢!

编辑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)])
        }
    }
}

2 个答案:

答案 0 :(得分:3)

在重新填充快照文档之前,必须重置

messages阵列。您可以在行self.messages.removeAll()

前添加for document in snapshot.documents

答案 1 :(得分:0)

您必须在

之后清除保存对象的数组
collectionView?.refreshControl?.beginRefreshing()
self.messages = []

然后致电

self.collectionView?.reloadData()

否则,您将收到“索引超出范围”错误