我将Cloud Firestore用作iOS应用程序的数据库。
当文档包含地图(对象类型)时,我想查询数据时遇到问题。我无法通过简单的查询来访问地图(nameOnId)的字段(例如:firstName)。
我的代码如下:
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)") }}}
我在某处读到,为了能够访问map对象内的值,我需要展平map对象,但是拥有该对象无法访问它们,我唯一能进入的就是映射中的一组值,因此它仅显示它们的键和值,例如:
{
firstName = "John";
middleName = "British";
middleName = "Citizen";
gender = "M";
DOB = "8 December 2000 at 00:00:00 UTC+11";
}
问题是如何使用查询访问“ John”之类的单个值?My data structure on Cloud Firestore
答案 0 :(得分:1)
一种实现方法如下。同样好的做法是不强制打开您的querySnapshot(如果查询不存在,则您的应用程序将崩溃!)。希望这会有所帮助!
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)
}
}
}
}