0

Imagine there is cooking app that the user can create their own recipes. The app is integrated with Firebase and gets the core data from Firebase. In a view, I let the user to create the recipe. So user will input name, ingredients with their sizes and equipment. Somehow I need to store this data to use it within the View and then save it on Firebase once the user press the save button. How can I store this data temporarily? The data will be something like the below example. A mixture of arrays and objects.

{
  "User": 124213,
  "RecipeName": "Some Name",
  "createdDate": "Some Date",
  "Ingredients": [
    {
      "ingredient": 123,
      "size": 3
    },
    {
      "ingredient": 234,
      "size": 3
    },
    {
      "ingredient": 294,
      "size": 2
    },
    {
      "ingredient": 736,
      "size": 2
    },
    {
      "ingredient": 150,
      "size": 4
    }
  ],
  "Equipment": [
    [ 123, 234 ],
    [ 294, 736 ]
  ]
}

I dont know how developer deal with such situation where they need to keep data temporarily on IOS before sending it to Firebase.

Any idea or suggestion is appreciated.

Danny
  • 129
  • 1
  • 8

1 Answers1

1

Define your data structure using structs or classes depending on your needs and conform them to codable:

struct Recipe: Codable {
let user: Int
let recipeName, createdDate: String
let ingredients: [Ingredient]
let equipment: [[Int]]

enum CodingKeys: String, CodingKey {
    case user = "User"
    case recipeName = "RecipeName"
    case createdDate
    case ingredients = "Ingredients"
    case equipment = "Equipment"
 }
}

   // MARK: - Ingredient
   struct Ingredient: Codable {
   let ingredient, size: Int
   }

Once you need to post your data to Firebase convert it to JSON and post it.

let dataRecipe = try? JSONEncoder().encode(myRecipeObject) 
Andrew
  • 885
  • 1
  • 10
  • 15
  • Thanks very helpful. I posted a question regarding updating values in this struct [here](https://stackoverflow.com/questions/61977451/how-to-update-the-values-of-a-struct-in-a-view). It would be great if you answer that. – Danny May 23 '20 at 19:23