Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import SwiftUI
- struct AddRecipeView: View {
- @State private var name = ""
- @State private var description = ""
- @State private var estimatedTime = ""
- @State private var imageName = ""
- @State private var showingImagePicker = false
- var body: some View {
- VStack {
- TextField("Nazwa", text: $name)
- .textFieldStyle(RoundedBorderTextFieldStyle())
- .padding()
- TextField("Opis", text: $description)
- .textFieldStyle(RoundedBorderTextFieldStyle())
- .padding()
- TextField("Czas przygotowania", text: $estimatedTime)
- .textFieldStyle(RoundedBorderTextFieldStyle())
- .padding()
- Button(action: {
- showingImagePicker = true
- }) {
- Text("Dodaj zdjęcie")
- .font(.headline)
- .padding()
- .background(Color.blue)
- .foregroundColor(.white)
- .cornerRadius(10)
- }
- .padding()
- .sheet(isPresented: $showingImagePicker) {
- ImagePicker(imageName: $imageName)
- }
- Button(action: {
- print("Przycisk 'Zapisz przepis' został naciśnięty")
- saveRecipe()
- }) {
- Text("Zapisz przepis")
- .font(.headline)
- .padding()
- .background(Color.green)
- .foregroundColor(.white)
- .cornerRadius(10)
- }
- .padding()
- Spacer()
- }
- .padding()
- .navigationTitle("Dodaj przepis")
- }
- func saveRecipe() {
- print("Rozpoczęto zapisywanie przepisu")
- let newRecipe = MyRecipe(filename: imageName, name: name, description: description, estimatedTime: estimatedTime)
- saveToJSON(recipe: newRecipe)
- }
- func saveToJSON(recipe: MyRecipe) {
- guard let url = Bundle.main.url(forResource: "recipes", withExtension: "json") else {
- print("Nie znaleziono pliku recipes.json")
- return
- }
- do {
- let data = try Data(contentsOf: url)
- var recipes = try JSONDecoder().decode([MyRecipe].self, from: data)
- recipes.append(recipe)
- let newData = try JSONEncoder().encode(recipes)
- try newData.write(to: url)
- print("Przepis zapisany pomyślnie")
- } catch {
- print("Błąd zapisu do JSON: \(error)")
- }
- }
- }
- struct MyRecipe: Identifiable, Codable {
- var id = UUID()
- var filename: String
- var name: String
- var description: String
- var estimatedTime: String
- enum CodingKeys: String, CodingKey {
- case filename
- case name
- case description
- case estimatedTime
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement