how to get documents id's from a collection with swift from firestore

Viewed 1162

i want to get document's id's from firestore and store them in a variable to use in my next page.

how can i do this with swift? i tried this method but it generates a random id not the specific document id of the collection that i have

let docRef = Firestore.firestore().collection("Shops").document()
let docId = docRef.documentID

attached are the document id's i need to retrieve in my variable.

these are the id's i need to retrieve in my variable

1 Answers

You can use getDocuments() to fetch all documents in one collection or use .addSnapshotListener() to automatically fetch new documents.

Firestore.firestore().collection("Shops").getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID)") // Get documentID
            print("\(document.data)") // Get all data
            print("\(document.data()["name"] as! String)") // Get specific data & type cast it.
        }
    }
}
Related