【问题标题】:Facing issues in Chat Pagination聊天分页面临的问题
【发布时间】:2020-08-09 21:12:26
【问题描述】:

我正在运行代码以在 swift iOS 聊天应用程序中加载聊天。聊天应用程序中的问题是在运行应用程序时函数 paginateData() 中的“query in else{}”,第一个“query in if{}”按预期顺利运行,但在另一个没有运行。我正在使用 firestore 数据库来实现聊天。 我的目标是对聊天室中的聊天进行分页。如果需要更多信息,请告诉我。

代码

func paginateData() {
    fetchingMore = true
    var query: Query!

    if messages.isEmpty {
        query = Firestore.firestore().collection("messageRoom").document(messageRoomIdFinal).collection("messages").order(by: "timestamp", descending: false).limit(to: 20)
        print("First 20 Messages loaded")
    } else {
        query = Firestore.firestore().collection("messageRoom").document(messageRoomIdFinal).collection("messages").order(by: "timestamp", descending: false).start(afterDocument: lastDocumentSnapshot).limit(to: 7)
        print("Next 7 Messages loaded")
    }

    query.addSnapshotListener { (snapshot, err) in
        if let err = err {
            print("\(err.localizedDescription)")
        } else if snapshot!.isEmpty {
            self.fetchingMore = false
            return
        } else {
            snapshot!.documentChanges.forEach { diff in
                if (diff.type == .added) {
                    let snap = diff.document
                    let aMessage = Message(withSnap: snap)
                    self.messages.append(aMessage)
                    DispatchQueue.main.async {
                        self.collectionView.reloadData()
                        let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
                        self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
                    }
                }

                if (diff.type == .modified) {
                    let docId = diff.document.documentID
                    DispatchQueue.main.async {
                        self.collectionView.reloadData()
                        let indexPath = IndexPath(item: self.messages.count - 1, section: 0)
                        self.collectionView.scrollToItem(at: indexPath, at: .bottom, animated: true)
                    }
                    //update the message with this documentID in the array
                }

                if (diff.type == .removed) {
                    let docId = diff.document.documentID
                    //remove the message with this documentID from the array
                }

                self.lastDocumentSnapshot = snapshot!.documents.last
            }
        }
    }
}

【问题讨论】:

  • 欢迎来到 SO。请花时间格式化您的代码,使其易于阅读。您还有一个错字.collectioncollection("messageRoom"),目前还不清楚哪条线路在 nil 上崩溃。此外,您不需要在 Firebase 函数闭包中使用 DispatchQueue.main.async,因为 UI 调用在主线程上运行。最后,这个snapshot! 是危险的,因为你不安全地打开一个可选项,如果它为 nil 就会崩溃(提示提示)。请通过安全地解包选项来保护您的代码和您的用户。
  • @Jay 我已经编辑了这个问题,之前的问题是通过添加“self.lastDocumentSnapshot = snapshot!.documents.last”来解决的,但是现在我无法在 func 中执行“else 查询”分页数据()”。感谢以上指导
  • 我为您格式化了您的代码,使其易于阅读。请花点时间自己做这件事,因为疯狂的格式很难阅读,并且可能导致问题被关闭。
  • @Jay 感谢您的格式化,我会在以后处理这个问题,您能帮我把代码按要求准确吗

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


【解决方案1】:

与问题无关,但 Firebase 闭包中的 UI 调用在主线程上运行,因此您可以删除 DispatchQueue。

我不认为您的代码离我们很远。我重写了它以按年龄分页加载用户 3 并且下面的代码可以正常工作。

查看并与您的代码进行比较。每次调用它时,它都会加载接下来的三个用户。

var lastDocumentSnapshot: DocumentSnapshot?

func observeUsersWithPagination() {
    var query: Query!

    let usersCollectionRef = self.db.collection("users")

    if let nextStartingSnap = self.lastDocumentSnapshot {
        query = usersCollectionRef.order(by: "age", descending: false).start(afterDocument: nextStartingSnap).limit(to: 3)
    } else {
        query = usersCollectionRef.order(by: "age", descending: false).limit(to: 3)
    }

    query.addSnapshotListener { querySnapshot, error in
        guard let snapshot = querySnapshot else {
            print("Error fetching snapshots: \(error!)")
            return
        }

        self.lastDocumentSnapshot = snapshot.documents.last

        snapshot.documentChanges.forEach { diff in
            let userName = diff.document.get("name") as? String ?? "No Name"
            let age = diff.document.get("age") as? Int ?? 0
            if (diff.type == .added) {
                print("Added user: \(userName)", age)
            }
            if (diff.type == .modified) {
                print("Modified user: \(userName)", age)
            }
            if (diff.type == .removed) {
                print("Removed user: \(userName)", age)
            }
        }
    }
}

尚不清楚是否真的需要 documentChanges.forEach。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-10
    • 2020-06-10
    • 1970-01-01
    相关资源
    最近更新 更多