0

I have a SwiftUI app with no concept of persistence. It loads up a JSON file that has an array of 100 countries (sample below):

[
   {
     id: 1,
     name: "Algeria",
     favorited: false,
     flag: "blue",
     extended: false,
   },
   {
     id: 2,
     name: "Bolivia",
     favorited: false,
     flag: "green",
     extended: false,
   }
]

My Country model was:

model

struct Country: Codable, Identifiable {
   var id: Int,
   let name: String,
   let favorited: Boolean,
   let extended: Boolean,
   let flag: String
}

I've now decided to add persistence so that the boolean values could persist. So if a user favorites a country, it will be there again on app relaunch.

I removed my model above and create a Data Model called CountryModel and add the attributes and type to the file.

I then created a class for the Data Controller:

class DataController: ObservableObject {
    let container = NSPersistentContainer(name: "CountryModel")
    
    init() {
        container.loadPersistentStores { description, error in
            if let error = error {
                print("Err: \(error)")
            }
        }
    }
}

My root view is called MainView. I've added the DataController instance as a @StateObject but I don't know the next step to incorporate how I was previously handling the loading of the JSON file and holding that as @State. I'm stuck on how the next step. I want it to load up from JSON if the DataController is empty (first launch ever) but then copy over to CoreData so that all subsequent loads will read from CoreData and not rely on the JSON file anymore.

import SwiftUI

struct MainView: View {
    @State var countries: [Country] = Bundle.main.decode("Countries.json")
    
    @StateObject private var dataController = DataController() <-- newly added
    
    var favorites : [Country] {
        return countries.filter { $0.favorite }
    }
    
    var body: some View {
        TabView {
            ContentView(countries: $countries)
                .tabItem {
                    Label("Menu", systemImage: "list.dash")
                }
                .environment(\.managedObjectContext, dataController.container.viewContext) <-- newly added
            MapView()
                .tabItem {
                    Label("Map", systemImage: "square.and.pencil")
                }

.....

0 Answers0