2017-05-27 93 views
2

這個問題是一個跟進來自: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上。但我希望能夠採取措施,保​​存配料的全部配方。大多數例子給出了一組具有聲明屬性的字典。然而,我的配方可以是隨機的,因爲每個配方可以有隨機數量的配料

+0

,在一去,對不對?在此查詢中,databaseRef.child(「RecipeData」)。child(「recipe」)。updateChildValues(recipe) –

+0

正確,此時只存儲配方。我不知道如何儲存食材。 – Chace

+0

是否在Firebase上已有「IngredientData」:{ 「ingredients」:{__data__}}? –

回答

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) 
... 
要存儲成分與配方一起
+0

目前'ingredientText'只是一個來自textField插座的字符串。所以它實際上沒有必要。我會更新我的問題刪除。我現在如何在配方中存儲配料字典? – Chace

+0

我認爲最好的解決方案是手動將配料添加到配方中,如「-KkbWdomTYdpgEDLjC9w」:true'。那麼你知道我怎麼得到'-KkbWdomTYdpgEDLjC9w'的名字嗎? – Chace

+0

我不確定你的意思。我可以告訴你如何將它們手動添加到配方中。但目前我的addRecipe功能與我的配料沒有任何關係。 – Chace