Chace
Chace

Reputation: 561

Saving a Dictionary of key-values in Firebase using Swift

This question is a follow up from: Post Array to firebase Database in Swift

I am trying to save some ingredients into a recipe and later be able to retrieve the entire recipe with the ingredients inside it. After looking at the question above and this blog post https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html. I was able to re-structure my database

This is my Ingredient Dictionary:

{
  "IngredientDict": {
    "-KkbWdomTYdpgEDLjC9w": "Eggs",
    "-KkbWvaa5DT1PY7q7jIs": "Spaghetti",
    "-KkbaDQ8wYJxR3O2OwKd": "Parmesan"

      // More possible ingredients

  }
} 

This is my Ingredient Data:

{
  "IngredientData": {
    "ingredients": {
      "-KkbWdomTYdpgEDLjC9w": {
        "name": "Eggs",
        "uid": "-KkbWdomTYdpgEDLjC9w"
      },
      "-KkbWvaa5DT1PY7q7jIs": {
        "name": "Spaghetti",
        "uid": "-KkbWvaa5DT1PY7q7jIs"
      },
      "-KkbaDQ8wYJxR3O2OwKd": {
        "name": "Parmesan",
        "uid": "-KkY90e7dAgefc8zH3_F"

      // More possible ingredients

      }
    }
  }
}

I now want to add these set of ingredients to my recipe in one action. This is how I currently make a recipe:

@IBAction func addRecipe(_ sender: Any) {

        guard let itemNameText = recipeName.text else { return }

        guard itemNameText.characters.count > 0 else {

            print("Complete all fields")
            return
        }

        let recipeKey = databaseRef.child("RecipeData").child("recipe").childByAutoId().key
        let recipeItem: [String : Any] = ["recipeName" : itemNameText, "recipeID" : recipeKey]
        let recipe = ["\(recipeKey)" : recipeItem]

        databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)

        print("\(itemNameText) was added")
    }

This is the outcome:

{
  "RecipeData": {
    "recipe": {
      "-Kkv36b_aPl7HAO_VYaJ": {
        "recipeName": "Spaghetti Carbonara",
        "recipeID": "-Kkv36b_aPl7HAO_VYaJ"
      }
    }
  }
}

How do I add the ingredients? At the moment I can manually add it on the Firebase. But I would like to be able have an action that saves the entire recipe with the ingredients. Most examples give a dictionary with a set of declared properties. However mine can be random as each recipe can have random number of ingredients.

Upvotes: 1

Views: 3033

Answers (1)

Paulo Mattos
Paulo Mattos

Reputation: 19339

In your addRecipe function, try this:

...
let ingredients: [String] = ...
var ingredientsJSON = [String: Bool]()
for key in ingredients {
    ingredientsJSON[key] = true
}
let recipeJSON: [String : Any] = [
    "recipeName" : itemNameText,
    "recipeID" : recipeKey,
    "ingredients": ingredientsJSON
]
let recipe = ["\(recipeKey)" : recipeJSON]
databaseRef.child("RecipeData").child("recipe").updateChildValues(recipe)
...

Upvotes: 1

Related Questions