【问题标题】:How to read Firestore data from a Map field type?如何从 Map 字段类型中读取 Firestore 数据?
【发布时间】:2022-01-23 09:42:50
【问题描述】:

我的 Firestore 数据设置如下:

这就是我读取数据的方式:

for doc in snapshot!.documents {
                    
  let recipeFromFirestore = Recipe(
    glutenFree: doc["glutenFree"] as! Bool,
    dairyFree: doc["dairyFree"] as! Bool,
    cheap: doc["cheap"] as! Bool)
                    
  recipes.append(recipeFromFirestore)
}

这些是我的 RecipeExtendedIngredients 结构:

struct Recipe: Codable {
    var glutenFree: Bool?
    var dairyFree: Bool?
    var cheap: Bool?
    var extendedIngredients: [ExtendedIngredients]? = nil
}

struct ExtendedIngredients: Codable {
    var aisle: String?
    var image: String?
    var name: String?
    var amount: Double?
    var unit: String?
}

如何在 Firestore 的 extendedIngredients 字段中读取地图类型数据的 array?我不确定如何将其包含在我的 let recipeFromFirestore 代码中。

非常感谢任何帮助或指导!

【问题讨论】:

    标签: ios database firebase google-cloud-firestore


    【解决方案1】:

    我能够使用Codable API 获取我的所有数据,包括地图类型。

    docRef.getDocument { document, error in
                if let error = error as NSError? {
                    self.errorMessage = "Error getting document: \(error.localizedDescription)"
                }
                else {
                    if let document = document {
                        do {
                            self.recipe = try document.data(as: Recipe.self)
                            
            let recipeFromFirestore = Recipe(
            glutenFree: self.recipe!.glutenFree, 
            dairyFree: self.recipe!.dairyFree,
            cheap: self.recipe!.cheap,
            extendedIngredients: self.recipe!.extendedIngredients)
                            
                            self.recipes.append(recipeFromFirestore)
    
                        }
                        catch {
                            print("Line 136: \(error)")
                        }
                    }
                }
            }
    

    我不需要使用这种方法进行任何显式映射。

    【讨论】:

      猜你喜欢
      • 2021-03-08
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      相关资源
      最近更新 更多