使用Swift保存Firebase中的键值字典 [英] Saving a Dictionary of key-values in Firebase using Swift

查看:146
本文介绍了使用Swift保存Firebase中的键值字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是从一个后续:将数组发送到Swift中的firebase数据库



我试图将一些成分保存到食谱,以后可以用里面的配料检索整个配方。看了上面的问题和这篇博客文章 https: //firebase.googleblog.com/2014/04/best-practices-arrays-in-firebase.html 。我能够重新构建我的数据库

这是我的成分词典:

 IngredientDict:{
-KkbWdomTYdpgEDLjC9w:鸡蛋,
-KkbWvaa5DT1PY7q7jIs:意大利面条,
-KkbaDQ8wYJxR3O2OwKd: Parmesan

//更多可能的原料

}
}

这是我的成分数据:

  {
IngredientData:{
成分:{
-KkbWdomTYdpgEDLjC9w:{
name:Eggs,
uid:-KkbWdomTYdpgEDLjC9w
},
-KkbWvaa5DT1PY7q7jIs:{
name:Spaghetti,
uid:-KkbWvaa5DT1PY7q7jIs
},
-KkbaDQ8wYJxR3O2OwKd:{
name:Parmesan,
uid:-KkY90e7dAgefc8zH3_F

//更多可能的原料

}
}




$ b现在我想添加t这一套成分在我的食谱中的一个行动。这是我目前如何做一个配方:

pre $ 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添加)
}

这是结果:


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

如何添加配料?目前我可以手动将其添加到Firebase。但我希望能有一个行动,保存整个配方的成分。大多数例子给出了一组具有声明属性的字典。然而,我可以是随机的,因为每个配方可以有随机数量的成分。

在您的 addRecipe中 / code>函数,试试这个:

  ... 
let ingredients:[String] =。 ..
var ingredientsJSON = [String:Bool]()
为配料中的关键字{
ingredientsJSON [key] = true
}
let recipeJSON:[String:任何] = [
recipeName:itemNameText,
recipeID:recipeKey,
ingredients:ingredientsJSON
]
let recipe = [\(配方密钥):recipeJSON]
databaseRef.child(RecipeData)。child(recipe)。updateChildValues(recipe)
...
pre>

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.

解决方案

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

这篇关于使用Swift保存Firebase中的键值字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆