[SOLVED] How do I retrieve a key from a firestore document (using swift 4/ios)

Issue

In the firebase docs for firebase database there is info on flattening a database and a message app is used as an example.

https://firebase.google.com/docs/database/web/structure-data

 // Conversation members are easily accessible
  // and stored by chat conversation ID
  "members": {
    // we'll talk about indices like this below
    "one": {
      "ghopper": true,
      "alovelace": true,
      "eclarke": true
    },
    "two": { ... },
    "three": { ... }
  },

Under “members”/”one” each key is the name of a participating member in the chat. I’m pretty sure in firebase database there is a getKey method to get each key.

I have set up my database (using firestore instead of firebase) in a similar way but where each chat is a unique identifier and the document contains the members of the chat where the key is their firebase auth id eg.

var docsref: DocumentReference?
                    docsref = self.defaultStore?.colleection("chats").document(chatID)
                    docsref?.getDocument { (document, error) in

                        if let _ = document {

                            print("document!.data()")


                        } else {
                            print("Document does not exist")
                        }
                    }

And when I output:

print(document!.data())

I get [“2mHuccccxxxxxxxxxxk4wkIAt33”: 1] which is the firebase auth code of one of the participating chat members and a boolean.

I would like to get that key but wasn’t sure how.

Thanks.

Solution

I’m not sure if it’s the exact Syntax but self.defaultStore?.colleection might be a typo with the double E. It could also possibly be that you’re missing a step. You’re getting inside the chatID and you’re expecting to output the keys inside members without actually accessing it. I’d access members after .document(chatID)

Answered By – Daniel Dramond

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.