Another expansion of the Lunch Card app. I figured out my problem in the last thread so I started a new one.
Please see my last thread for code references.
To save List data without using Core Data — because that would be a bit of a hassle — I was told to use Codable to convert the array to Data and export that into a file.
Thing is; I don’t know how I’d convert cardsInfo into Data, furthermore, convert to JSON.
Once I figure out how to convert that to JSON and into writable data, I’ll pretty much be good to go.
Please see my last thread for code references.
To save List data without using Core Data — because that would be a bit of a hassle — I was told to use Codable to convert the array to Data and export that into a file.
Thing is; I don’t know how I’d convert cardsInfo into Data, furthermore, convert to JSON.
Once I figure out how to convert that to JSON and into writable data, I’ll pretty much be good to go.
Sorry for my poor suggestions which did not work well.
But once found, it is very simple.
A simple sample code:
You need to call cardsInfo.saveCards(), where cardsInfo is the right instance of CardsInfo, maybe some action closure in CardsView.
But once found, it is very simple.
A simple sample code:
Code Block import Foundation struct CardInfo: Identifiable, Codable { //<- Make `CardInfo` conform to `Codable` var name: String = "" var id: String = "" var cname: String = "" var code: String = "" } class CardsInfo: ObservableObject { @Published var newCard: CardInfo = CardInfo() @Published var cards: [CardInfo] = [] func add() { cards.append(newCard) } } //... extension CardsInfo { var dataUrl: URL { FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] .appendingPathComponent("cards.json") } func saveCards() { do { //Convert Array of `CardInfo` to `Data` let data = try JSONEncoder().encode(cards) //Write `Data` to a file specified by URL try data.write(to: dataUrl, options: .atomic) } catch { print(error) } } func loadCards() { do { if FileManager.default.fileExists(atPath: dataUrl.path) { return } //Read `Data` from a file specified by URL let data = try Data(contentsOf: dataUrl) //Convert `Data` to Array of `CardInfo` let cards = try JSONDecoder().decode([CardInfo].self, from: data) self.cards = cards } catch { print(error) } } }
You need to call cardsInfo.saveCards(), where cardsInfo is the right instance of CardsInfo, maybe some action closure in CardsView.