0
votes

The existing solutions are not working for me, I've tried. What I'm trying to do is to fetch messages in a thread that is stored on Firestore. This is the current structure of Chat collection:

enter image description here

As you can see this chat between user 1 and user 2 only has 2 messages and I'm trying to fetch these and also listen to new ones if they are added to thread. Here is the code of how I'm doing it:

func loadChat() {

    self.showWaitOverlayWithText("Loading")
    let db = Firestore.firestore().collection("Chats")
        .whereField("user1ID", isEqualTo: Auth.auth().currentUser?.uid ?? "Not Found User 1")
        .whereField("user2UID", isEqualTo: user2UID ?? "Not Found User 2")

    db.getDocuments { (querySnap, error) in
        if let error = error {
            print("Error: \(error)")
            return
        } else {
            let doc = querySnap?.documents.first

           doc?.reference.collection("thread").addSnapshotListener(includeMetadataChanges: true, listener: { (threadQuery, error) in
                //Never comes here
                for message in threadQuery!.documents {
                    self.removeAllOverlays()
                    print("Data: \(message.data())")
                }
            })
        }
    }
}

It never executes collection("thread").addSnapshotListner.

1
Is it printing an error? That is, it is entering the first scenario of the conditional statement (if let error = error {)David Chopin
no it never execute the addSnapShotListner partChaudhry Talha
Okay, so the issue is that let doc = querySnap?.documents.first is returning nil. Or, similarly, querySnap is equal to nil.David Chopin
found a stupid mistake the key name is User2ID not User2UIDChaudhry Talha
If that is the case, then the issue lies in this line let db = Firestore.firestore().collection("Chats").whereField("user1ID", isEqualTo: Auth.auth().currentUser?.uid ?? "Not Found User 1").whereField("user2UID", isEqualTo: user2UID ?? "Not Found User 2. Can you check what Auth.auth().currentUser?.uid and user2UID to make sure neither one is nil and that they are strings that match up with your database?David Chopin

1 Answers

0
votes

So, the issue was simply an incorrect key in the query, "user2UID" instead of "user2ID". We were able to pinpoint this issue by checking whether or not the optional values (doc, querySnap) were nil or not. doc was equal to nil, querySnap was not, but its document count was equal to zero. This helped us know that the issue was with the line

let db = Firestore.firestore().collection("Chats")
       .whereField("user1ID", isEqualTo: Auth.auth().currentUser?.uid ?? "Not Found User 1")
       .whereField("user2UID", isEqualTo: user2UID ?? "Not Found User 2")

I initially thought the issue would have been an inconsistency with the values, not the keys, on the backend. A second look by Chaundhry confirmed that there was an incorrect key.