使用Swift保存Firebase中的键值字典

这个问题是从Post Array到Swift中的firebase数据库的后续

我正在尝试将一些ingredients保存到recipe ,之后可以检索配料中的全部配方。 看了上面的问题和这个博客文章https://firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html 。 我能够重新构build我的数据库

这是我的成分词典:

 { "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 } } } } 

我现在想在这个动作中join这些配料。 这是我目前如何做一个配方:

 @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。 但我希望能够有一个行动,保存与配料的整个食谱。 大多数例子给出了一组具有声明属性的字典。 不过,我的配方可以是随机的,因为每个配方可以有随机数量的配料

在你的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) ...