Advertisement
Xaniasty

Untitled

Jun 12th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.01 KB | None | 0 0
  1. import SwiftUI
  2.  
  3. struct AddRecipeView: View {
  4. @State private var name = ""
  5. @State private var description = ""
  6. @State private var estimatedTime = ""
  7. @State private var imageName = ""
  8. @State private var showingImagePicker = false
  9.  
  10. var body: some View {
  11. VStack {
  12. TextField("Nazwa", text: $name)
  13. .textFieldStyle(RoundedBorderTextFieldStyle())
  14. .padding()
  15.  
  16. TextField("Opis", text: $description)
  17. .textFieldStyle(RoundedBorderTextFieldStyle())
  18. .padding()
  19.  
  20. TextField("Czas przygotowania", text: $estimatedTime)
  21. .textFieldStyle(RoundedBorderTextFieldStyle())
  22. .padding()
  23.  
  24. Button(action: {
  25. showingImagePicker = true
  26. }) {
  27. Text("Dodaj zdjęcie")
  28. .font(.headline)
  29. .padding()
  30. .background(Color.blue)
  31. .foregroundColor(.white)
  32. .cornerRadius(10)
  33. }
  34. .padding()
  35. .sheet(isPresented: $showingImagePicker) {
  36. ImagePicker(imageName: $imageName)
  37. }
  38.  
  39. Button(action: {
  40. print("Przycisk 'Zapisz przepis' został naciśnięty")
  41. saveRecipe()
  42. }) {
  43. Text("Zapisz przepis")
  44. .font(.headline)
  45. .padding()
  46. .background(Color.green)
  47. .foregroundColor(.white)
  48. .cornerRadius(10)
  49. }
  50. .padding()
  51.  
  52. Spacer()
  53. }
  54. .padding()
  55. .navigationTitle("Dodaj przepis")
  56. }
  57.  
  58. func saveRecipe() {
  59. print("Rozpoczęto zapisywanie przepisu")
  60. let newRecipe = MyRecipe(filename: imageName, name: name, description: description, estimatedTime: estimatedTime)
  61. saveToJSON(recipe: newRecipe)
  62. }
  63.  
  64. func saveToJSON(recipe: MyRecipe) {
  65. guard let url = Bundle.main.url(forResource: "recipes", withExtension: "json") else {
  66. print("Nie znaleziono pliku recipes.json")
  67. return
  68. }
  69.  
  70. do {
  71. let data = try Data(contentsOf: url)
  72. var recipes = try JSONDecoder().decode([MyRecipe].self, from: data)
  73. recipes.append(recipe)
  74. let newData = try JSONEncoder().encode(recipes)
  75. try newData.write(to: url)
  76. print("Przepis zapisany pomyślnie")
  77. } catch {
  78. print("Błąd zapisu do JSON: \(error)")
  79. }
  80. }
  81. }
  82.  
  83. struct MyRecipe: Identifiable, Codable {
  84. var id = UUID()
  85. var filename: String
  86. var name: String
  87. var description: String
  88. var estimatedTime: String
  89.  
  90. enum CodingKeys: String, CodingKey {
  91. case filename
  92. case name
  93. case description
  94. case estimatedTime
  95. }
  96. }
  97.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement