使用Swift

时间:2017-05-27 15:55:58

标签: ios swift dictionary firebase firebase-realtime-database

此问题来自:Post Array to firebase Database in Swift

我正在尝试将一些ingredients保存到recipe中,之后可以使用其中的成分检索整个食谱。在查看上面的问题和此博客文章https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html之后。我能够重新构建我的数据库

这是我的成分词典:

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

      // More possible ingredients

  }
} 

这是我的成分数据:

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

      // More possible ingredients

      }
    }
  }
}

我现在想在一个动作中将这些成分添加到我的食谱中。这就是我目前制作食谱的方式:

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

这是结果:

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

如何添加成分?目前我可以在Firebase上手动添加它。但我希望能够采取行动,用配料保存整个​​配方。大多数示例都为字典提供了一组声明的属性。然而,我的可以是随机的,因为每个食谱可以有随机数量的成分。

1 个答案:

答案 0 :(得分:1)

addRecipe功能中,试试这个:

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