How would I save custom data after the app closes?

426 Views Asked by At

I am trying to store data after the app closes and one of the things I need to store is a variable that uses this struct

struct ToDoTasks: Identifiable, Hashable, Encodable, Decodable {
    var id = UUID()
    var task: String
    var date: Date
}

The user can enter data where it is then stored here using the previous struct

@State var items:[ToDoTasks] = [ToDoTasks(task: "Test", date: Date())]

What would be the best way to save the items variable after the app closes?

I tried using @AppStorage but couldn’t get it to work.

1

There are 1 best solutions below

2
malhal On

In Apple's ScrumDinger sample they do the save in ScrumsView.swift like this:

@Environment(\.scenePhase) private var scenePhase
...
        .onChange(of: scenePhase) { phase in
            if phase == .inactive { saveAction() }
        }