ios - Firestore API 更改 - 如何解码对象

标签 ios swift firebase google-cloud-firestore

我对 Firestore 还是个新手,正在尝试了解如何使用它。我注意到在几个 SOF 问题和 Firestore loco 的某些部分中,Firestore 似乎可以返回特定类的对象而不是数据字典。

例如,在 doco(似乎已部分更新)中它说:

The previous example used getData() to get the contents of the document as a map, but it's often more convenient to use a custom object type. In Add Data, you defined a City class that you used to define each city. You can turn your document back into a City object by calling .getData(City.class).

但是紧随其后的代码示例看起来已更新:

let docRef = db.collection("cities").document("BJ")

docRef.getDocument { (document, error) in
    if let city = document.flatMap({ City(dictionary: $0.data()) }) {
        print("City: \(city)")
    } else {
        print("Document does not exist")
    }
}

并且正在使用 init 来传递字典。

有谁知道 Firestore 是否会在对象解码中包含字典?据我目前所知,它似乎已删除或不可用。

最佳答案

抱歉,如果我没听清楚,但如果你想在 Swift 中找到城市对象类,它就在这里。

struct City {

    let name: String
    let state: String?
    let country: String?
    let capital: Bool?
    let population: Int64?

    init?(dictionary: [String: Any]) {
        guard let name = dictionary["name"] as? String else { return nil }
        self.name = name

        self.state = dictionary["state"] as? String
        self.country = dictionary["country"] as? String
        self.capital = dictionary["capital"] as? Bool
        self.population = dictionary["population"] as? Int64
    }

}

关于ios - Firestore API 更改 - 如何解码对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48197401/

相关文章:

ios - 在 SIMULATOR 和 DEVICE 中执行时无法识别字体

html - UIWebview - 文本切割

iOS App Today 扩展未上传到物理设备

ios - 如何在 iOS 中将字符串变量分配给标签或文本字段

ios - SERVICE_PLIST : GoogleService-Info. 找不到 plist

ios - 更新用户界面 Swift

swift - 从 firebase 数据库中删除

ios - 如何定义适当的约束以使 ScrollView 有效工作

java - 将 Android Studio 项目连接到 Firebase 数据库时出现问题

firebase - 使用 Flutter Firebase 存储插件上传文件