Learn Courses My Dashboard

How to read Firestore data from a Map field type?

My Firestore data is set up like this:

This is how I’m reading the data:

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)
}

These are my Recipe and ExtendedIngredients structs:

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?
}

How can I go about reading the array of Map type data in my extendedIngredients field in Firestore? I’m not sure how to include that in my let recipeFromFirestore code. I’ve tried the following but it doesn’t work:

for doc in snapshot!.documents {
                    
  let recipeFromFirestore = Recipe(
    glutenFree: doc["glutenFree"] as! Bool,
    dairyFree: doc["dairyFree"] as! Bool,
    cheap: doc["cheap"] as! Bool,
    ExtendedIngredients(aisle: doc["aisle"] as? String, image: doc["image"] as? String, name: doc["name"] as? String, amount: doc["amount"] as? Double, unit: doc["unit"] as? String)])
   
  recipes.append(recipeFromFirestore)
}

When I run print(doc.data()), I can see that the data is there but I don’t know how to assign it to my Recipe and ExtendedIngredients structs.

Any help or guidance is much appreciated!

0

I was able to get all of my data, including the Map type by using the 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)")
                    }
                }
            }
        }

I did not need to do any explicit mapping with this approach.