如何从Firebase中的文档中获取单个项目?
我可以使用以下代码获取所有元素:
let key = UserDefaults.standard.value(forKey: "uid") as! String
let docRef = firebaseDB.collection("user").document(key)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let dataDescription = document.data().map(String.init(describing:))
print("Document data: \(dataDescription)")
} else {
print("Document does not exist")
}
}
我只希望获得姓名和电话号码。如何过滤结果?
答案 0 :(得分:0)
FirebaseFirestore有一种方便的方式来缓存单个文档:
首先,您需要通过ID指定文档:
let key = UserDefaults.standard.value(forKey: "uid") as? String ?? "Null" // Unique user key
let docRef = db.collection("user").document(key)
获取文档:
docRef.getDocument { (document, error) in
if let document = document, document.exists {
let docData = document.data()
// Do something with doc data
} else {
print("Document does not exist")
}
}
访问文档数据:
let status = docData!["phone"] as? String ?? ""