Firestore分页查询未返回所有结果

时间:2020-03-20 21:48:15

标签: ios swift xcode google-cloud-firestore pagination

我实现了分页Firestore查询,一次返回结果5。

首先从创建一个侦听器并提取5个结果开始。上拉刷新时,它还会拉出5个结果。在第二次刷新时由于某种原因刷新了10个结果。在第三次刷新时,它不会获得任何结果。查看数据后,某些数据丢失。

下面是我的MessageListener函数:

func createMessageListener() {
    reference = db.collection(["chats", channel.id!, "messages"].joined(separator: "/"))

    let first = reference?.order(by: "created", descending: true).limit(to: 5)

    messageListener = first!.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
            self.handleDocumentChange(change)
            self.updateReadStatus()
        }

        guard let lastSnapshot = snapshot.documents.last else {
            // The collection is empty.
            self.hasMoreMessages = false
            return
        }

        self.last = self.reference?.order(by: "created", descending: true).start(afterDocument: lastSnapshot).limit(to: 5)
    }
}

以下是我的loadMoreMessages函数:

func loadMoreMessages() {

    if hasMoreMessages {
        last!.addSnapshotListener { querySnapshot, error in
            guard let snapshot = querySnapshot else {
                print("Error listening for channel updates: \(error?.localizedDescription ?? "No error")")
                self.hasMoreMessages = false
                self.delegate.viewModelDidLoadMoreMessages(hasMoreMessages: self.hasMoreMessages)
                return
            }
            self.moreMessagesLoaded = true
            snapshot.documentChanges.forEach { change in
                self.handleDocumentChange(change)
            }
            self.delegate.viewModelDidLoadMoreMessages(hasMoreMessages: true)

            guard let lastSnapshot = snapshot.documents.last else {
                // The collection is empty.
                self.hasMoreMessages = false
                return
            }

            self.last = self.reference?.start(afterDocument: lastSnapshot)
        }
    } else {
        self.delegate.viewModelDidLoadMoreMessages(hasMoreMessages: self.hasMoreMessages)
    }
}

不太清楚发生了什么。如果在create listener函数中,我将第一个限制更改为35。它将提取所有数据。

在此先感谢您的帮助

0 个答案:

没有答案