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!