0

This function saves data into Firestore.

static func createRecipe(docId:String, ingredientsAmount:Int, ingredientsName:String, completion: @escaping (Recipe?) -> Void) {
        
let db = Firestore.firestore()
        
        db.collection("recipes").document(docId).setData(
            [
             "title":title,
             "ingredients": [
                ["amount": ingredientsAmount,
                 "name": ingredientsName]
             ]
            ]) { (error) in
             }
    }

I'm using Codable to parse the data from an external source. But I have only been able to save one item at a time from the ingredients array.:

                do {
                    let decoder = JSONDecoder()
                    let recipe = try decoder.decode(Recipe.self, from: data!)

                    let uuid = UUID().uuidString
                    
                    createRecipe(
                        docId:uuid,
                        title: recipe.title ?? "",
                        ingredientsAmount: Int(recipe.ingredients?[0].amount ?? 0), // How to save EVERY item in recipe?
                        ingredientsName: recipe.ingredients?[0].name ?? "", // How to save EVERY item in recipe?
                    ) { recipeURL in
                        print("success")
                    }
                }
                catch {
                    print("Error parsing response data: \(error)")
                }

I can tell that I'm parsing the JSON data successfully because the following outputs every item in the ingredients array:

                    for eachIngredient in recipe.ingredients! {
                        print(eachIngredient.name)
                        print(eachIngredient.amount)
                    }

How can I save every item in the ingredients array to Firestore?

Any guidance is much appreciated!

1 Answer 1

1

I'd suggest passing an array of Ingredients to the function and then using map to create the dictionaries:

static func createRecipe(docId:String, title: String, ingredients: [Ingredient], completion: @escaping (Recipe?) -> Void) {
    
    let db = Firestore.firestore()
    
    db.collection("recipes").document(docId).setData(
        [
            "title": title,
            "ingredients": ingredients.map { ["name": $0.name, "amount": $0.amount] }
        ])
        { (error) in
            //handle error
        }
}

Keep in mind that there's also a setData(from:) that takes a Codable, so since Recipe is Codable, you should just be able to do this (assuming recipe is a Recipe type):

try db.collection("recipes").document(docId).setData(from: recipe)

Documentation for the above function

Sign up to request clarification or add additional context in comments.

1 Comment

The last comment about Codable was EXACTLY what I needed! What an elegant solution. Thank you so much!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.