I am trying to keep the data entered by the user stored on the device (through a file), when the user closes the app and relaunches it. Currently it just always shows the sample data when the app was quit (swiped up).
.onAppear {
collections = loadCollections()
if collections.isEmpty {
addSampleCollection()
}
}
.onDisappear {
saveCollections(collections: collections)
}
}
func delete(at offsets: IndexSet) {
collections.remove(atOffsets: offsets)
}
func saveCollections(collections:[Collection]){
do {
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml // or .binary for binary format
let data = try encoder.encode(collections)
let fileURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("Collections.plist")
try data.write(to: fileURL)
} catch {
print("Error saving collections to property list: \(error)")
}
}
func loadCollections() -> [Collection] {
do {
let fileURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("Collections.plist")
let data = try Data(contentsOf: fileURL)
let decoder = PropertyListDecoder()
return try decoder.decode([Collection].self, from: data)
} catch {
print("Error loading collections from property list: \(error)")
return []
}
}
func addSampleCollection() {
let sampleCollection = Collection(title: "Sample Collection", description: "This is a sample collection", items: [
Item(title: "Item 1"),
Item(title: "Item 2"),
Item(title: "Item 3")
])
collections.append(sampleCollection)
}
}
This is an extract from my ContentView.