Hey @JimOlivi love that you’re taking on this challenge! So cool, I often learn the best from challenges myself let us know how it goes via a Journal!
In the iOS Databases module six, Chris teaches you how to accept user input via a Form, then create a new Core Data object, and save it as a Recipe. I just finished this module myself, so you can see my full repo here.
To do this, I use a Button
to execute a method that will save the object to the Core Data store. I use NavigationView
s, when I want the user to go to a new View after clicking something instead, and Buttons, when I want a piece of code executed, e.g. saving to the Core Data database.
// Add button
Button("Add") {
// Calls the method to add the new recipe to core data
addRecipe()
// Calls the method that clears the State properties in the form
clear()
// Switch the View to the list view
tabSelection = Constants.listTab
}
To do all this, first, you define @State
properties to hold the user input:
// MARK: - Define Recipe Properties
@State private var name = ""
@State private var summary = ""
@State private var prepTime = ""
@State private var cookTime = ""
@State private var totalTime = ""
// Even though this is an Integer in the Data Store, accept the input as a string
@State private var servings = ""
Next, you need a method to accept this new data, create a new Core Data object, then save it:
/// Saves the Recipe to Core Data based on the filled out information, then transitions the View back to the
/// Recipe List View.
func addRecipe() {
// Create a new Core Data Recipe object
let newRecipe = Recipe(context: viewContext)
// Add all the properties to this new Core Data object using the State properties
newRecipe.name = name
newRecipe.summary = summary
newRecipe.prepTime = prepTime
newRecipe.cookTime = cookTime
newRecipe.totalTime = totalTime
newRecipe.servings = Int(servings ) ?? 1
newRecipe.highlights = highlights
newRecipe.directions = directions
// Convert the UIImage to a binary type of image
newRecipe.image = recipeImage?.pngData()
// For each of the directionsingredients add it to the recipe
for ingredient in ingredients {
// Create Core Data Ingredient
let coreDataIngredient = Ingredient(context: viewContext)
coreDataIngredient.id = UUID()
coreDataIngredient.name = ingredient.name
coreDataIngredient.num = ingredient.num ?? 1
coreDataIngredient.denom = ingredient.denom ?? 1
coreDataIngredient.unit = ingredient.unit
// Reference back to the parent recipe
// coreDataIngredient.recipe = newRecipe
// Add the ingredient to the recipe
newRecipe.addToIngredients(coreDataIngredient)
}
// Save to Core Data
do {
// Attempts to save
try viewContext.save()
}
catch {
// Displays any errors
print(error.localizedDescription)
}
}
How the whole form looks (in Chris fashion, he shows you SO much other stuff too, like accepting a photo from the user, or allowing him or her to use a camera):