Reload NSPersistentCloudKitContainer from a SwiftUI View - MVVM

How can I reload the NSPersistentCloudKitContainer from a SwiftUI View?

I have a SwiftUI + MVVM + CloudKit app that successfully syncs to CloudKit but what I would like to be able to do is reload the NSPersistentCloudKitContainer from some View in the app to be able to evaluate if the app should sync to CloudKit or not by setting the cloudKitContainerOptions to nil (description.cloudKitContainerOptions = nil) if the user doesn't want to sync.

In other words, I need to reload the code inside the init() method in the CoreDataManager file when a method in the View Model is called. See the code and comments below.

Here is the code...

Core Data Manager

    class CoreDataManager{    
            static let instance = CoreDataManager()

            let container: NSPersistentCloudKitContainer
            let context: NSManagedObjectContext
            
            init(){
                container = NSPersistentCloudKitContainer(name: "CoreDataContainer")
                
                guard let description = container.persistentStoreDescriptions.first else{
                    fatalError("###\(#function): Failed to retrieve a persistent store description.")
                }

                description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
                description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
                
                /// This is the code that I would like to control from other view in the app
                /// if iCloudSync is off, do nothing otherwise set it to nil
                if !iCloudSync{
                    description.cloudKitContainerOptions = nil
                }

                container.loadPersistentStores { (description, error) in
                    if let error = error{
                        print("Error loading Core Data. \(error)")
                    }
                }
                container.viewContext.automaticallyMergesChangesFromParent = true
                context = container.viewContext
            }
            
            func save(){
                do{
                    try context.save()
                    print("Saved successfully!")
                }catch let error{
                    print("Error saving Core Data. \(error.localizedDescription)")
                }
            }
        }

View Model

Somehow I would like to be able to have a way to control the reload process in the View Model.

        class CarViewModel: ObservableObject{
            let manager = CoreDataManager.instance
            @Published var cars: [Car] = []
            
         init(){
                getCars()
            }
            func addCar(){}
            func getCars(){}
            func deleteCar(){}

            func save(){
                self.manager.save()
            }
        }

SwiftUI View

Then from a view, I would like to control the reload process through the View Model by calling a method.

    struct ContentView: View {
        @State private var isSync = false
        @StateObject var viewModel = CarViewModel()

        var body: some View {
            VStack {
                Toggle("iCloud Sync", isOn: $isSync)
                    .toggleStyle(SwitchToggleStyle(tint: .red))

                if isSync {
                    // RELOAD the container, something like this
                    viewModel.reloadContainer(withSync: true)
                }
            }
        }
    }

Any help would be appreciated.

Thanks

Replies

Did you find a solution?