Hi have a question to the following code:
If i append something in the AddView, i want to save it in the UserDefaults and append it automatically when the app starts. But I don't know how to do this. Can you help me ?
PS: I'm using AppDelegate and SceneDelegate.
Code Block Swift struct ContentView: View { @State private var listItems = [Item]() let savedItems = UserDefaults.standard.string(forKey: "Items") ?? "error" var body: some View { NavigationView{ List{ ForEach(listItems){ item in Text(item.name) } NavigationLink( destination: AddView(listItems: $listItems), label: { Text(" Add") .foregroundColor(.blue) }) } .navigationBarTitle("MyApp") } } }
Code Block Swift struct AddView: View { @State var text:String = "" @Binding var listItems: [Item] var body: some View { VStack{ TextField("Name", text: $text).padding().background(Color(.systemGray5)).frame(width: 400,alignment: .center).cornerRadius(20) Button(action: { listItems.append(Item(name: text, image: "Gif")) print(listItems) UserDefaults.standard.set(listItems, forKey: "Items") }, label: { Text("Add") }) } } }
If i append something in the AddView, i want to save it in the UserDefaults and append it automatically when the app starts. But I don't know how to do this. Can you help me ?
PS: I'm using AppDelegate and SceneDelegate.
You are saving the listItems like this
which means you can load this array on launch like this
Code Block Swift UserDefaults.standard.set(listItems, forKey: "Items")
which means you can load this array on launch like this
Code Block Swift .onAppear { listItems = (UserDefaults.standard.array(forKey: "Items") ?? [Item]()) as [Item] }