Reputation: 1311
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?
Upvotes: 3
Views: 10221
Reputation: 1143
Add an id attribute to your list struct:
struct List {
var name:String
var description:String
var id: String?
var dictionary:[String:Any] {
return [
"name":name,
"description":description
]
}
}
Then when mapping your documents manually assign the id attribute:
list = documents.compactMap{ (queryDocumentSnapshot) -> List? in
var listItem = try? queryDocumentSnapshot.data(as: List.self)
listItem?.id = queryDocumentSnapshot.documentID
return listItem
}
Upvotes: 0
Reputation: 655
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)")
}
Upvotes: 9
Reputation: 1311
I'm not positive if this is the best way but I appended to the listArray and it seems to work.
self.listArray.append(List(name: document["name"] as! String, description: document["description"] as! String, documentId: document.documentID))
Upvotes: 0