具有文档ID的Swift Firebase自定义对象

问题描述 投票:0回答:2

是否可以创建自定义Swift对象,将Firebase文档ID分配给Object参数?

从此处获取的代码: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)")
    }
}
}```
swift firebase swiftui
2个回答
2
投票

问题中的代码从文档中获取信息并将其映射到城市对象。如果您要将documentId分配给该城市对象,则可以执行此操作

switch result {
case .success(let city):
    if var city = city {
        city.docId = document!.documentID
        print("City: \(city)")
    } else {
        print("Document does not exist")
    }
case .failure(let error):
    print("Error decoding city: \(error)")
}

注意var city,然后可以使用以下方式为其分配文档ID:>

city.docId = document!.documentID  //please safely unwrap optionals (!)

并且不要忘记这个

public struct City: Codable {
   var docId = ""    //needs to be a var
   let name: String

0
投票

使用我们最近在Firestore中添加的Codable支持,还有一种更简单的方法来实现此目的:

© www.soinside.com 2019 - 2024. All rights reserved.