Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Firestore Get Document ID

I'm using FirebaseFirestore for my database.

I have an array of Lists with a name and description. I'd also like to grab each lists unique documentId. Is this possible?

List.swift

struct List {
    var name:String
    var description:String

    var dictionary:[String:Any] {
        return [
            "name":name,
            "description":description
        ]
    }
}

ListTableViewController.swift

func getLists() {
    if Auth.auth().currentUser != nil {
        db.collection("lists").getDocuments { (querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                self.listArray = querySnapshot!.documents.flatMap({List(dictionary: $0.data())})
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }
        }
    }
}

I found you can get the documentId by doing...

    for document in querySnapshot!.documents {
        print("\(document.documentID) => \(document.data())")
    }

But how do I store this in my List to be able to call later?

like image 357
pjmanning Avatar asked Feb 11 '26 13:02

pjmanning


1 Answers

1.Suppose you are getting documents in snapshot.

    guard let documents = ducomentSnapshot?.documents else {
      print("Error fetching documents: \(error!)")
      return
   }

// Get documentId of each document objects using this code.

  for i in 0 ..< documents.count {
        let dictData = documents[i].data()
        let documentID = documents[i].documentID
        print("Document ID \(documentID)")
    }
like image 166
Dhruv Narayan Singh Avatar answered Feb 14 '26 01:02

Dhruv Narayan Singh