【发布时间】:2020-08-07 03:29:07
【问题描述】:
有没有办法创建自定义 Swift 对象,我将 Firebase 文档 ID 分配给对象参数?
代码取自这里:https://firebase.google.com/docs/firestore/query-data/get-data#custom_objects
public struct City: Codable {
let id: String // here I'd like to fill in the Document ID
let name: String?
let state: String?
let country: String?
let isCapital: Bool?
let population: Int64?
enum CodingKeys: String, CodingKey {
case id = //Document ID
case name
case state
case country
case isCapital
case population
}
}
获取 Firebase 文档并创建对象。代码也取自上面的 Goolge Firebase 链接。
fun getObject(){
let db = Firestore.firestore()
let docRef = db.collection("cities").document("BJ")
docRef.getDocument { (document, error) in
if let error = error {
print("Error retrieving document: \(error)")
return
}
let result = Result {
try document?.data(as: City.self)
}
switch result {
case .success(let city):
if let city = city {
// A `City` value was successfully initialized from the DocumentSnapshot.
print("City: \(city)")
} else {
// A nil value was successfully initialized from the DocumentSnapshot,
// or the DocumentSnapshot was nil.
print("Document does not exist")
}
case .failure(let error):
// A `City` value could not be initialized from the DocumentSnapshot.
print("Error decoding city: \(error)")
}
}
}```
【问题讨论】: