问题
I am using Cloud Firestore as a Database for my iOS App.
I have an issue while I want to query my data when the document contains Maps (Object Type). I can not access the fields (say: firstName here) of a map (nameOnId) by having the simple query.
My code is as bellow:
let db = Firestore.firestore()
db.collection("userDetails").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let results = document.data()
let result2 = results.compactMap({$0})
print("listedItems: \(document.documentID) => \(result2[0].value)") }}}
I read somewhere that in order to be able to access the values inside the map object, I need to flatten the map object, but having that does not give me access to them, the only thing that I could get into are a group of values inside the map so it only shows the keys and values for them like:
{
firstName = "John";
middleName = "British";
middleName = "Citizen";
gender = "M";
DOB = "8 December 2000 at 00:00:00 UTC+11";
}
the question is how to get access to a single value like "John" using the query?My data structure on Cloud Firestore
回答1:
One way of doing it is as follows. Also its good practice to not force unwrap your querySnapshot (if the query does not exist, your app will crash!). Hope this helps!
let db = Firestore.firestore()
db.collection("userDetails").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else if let querySnapshot = querySnapshot {
for document in querySnapshot.documents {
let results = document.data()
if let idData = results["nameOnID"] as? [String: Any] {
let firstName = idData["firstName"] as? String ?? ""
print(firstName)
}
}
}
}
来源:https://stackoverflow.com/questions/52916414/how-to-get-data-from-a-map-object-cloud-firestore-document-on-swift-4-2