Столкнувшиеся проблемы в разбиении на страницы чата - PullRequest
0 голосов
/ 26 апреля 2020

Я запускаю код для загрузки чатов в быстром iOS приложении чата. Проблема в приложении чата заключается в «запросе в другом {}» в функции paginateData () во время работы приложения, первый «запрос в случае {}» выполняется гладко, как и ожидалось, но в другом не выполняется. Я использую базу данных 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
            }
        }
    }
}

1 Ответ

1 голос
/ 26 апреля 2020

Не имеет отношения к вопросу, но вызовы пользовательского интерфейса в замыканиях Firebase выполняются в главном потоке, поэтому вы можете удалить 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 необходим.

...