How to enable/disable cloudkit in runtime.

I am trying to implement toggling iCloud sync in runtime for my App, i.e. when users toggle the switch in my app, a persistent container will be created according to sync on or off. it works when relaunching the app after changing the container, but how to do it in runtime? how to reload data from the new container and refresh into UIs which already contain the old data from the previous container?

I searched all over the internet but could not find a solution to toggle iCloud sync in runtime properly.

Below is the code from my core data stack:

lazy var persistentContainer: NSPersistentContainer = {

       setupPersistentContainer()

    }()

    private func setupPersistentContainer() -> NSPersistentContainer {

        let isSyncOn = UserDefaults.standard.bool(forKey: "isSyncOn")

         let container = isSyncOn ? NSPersistentCloudKitContainer(name: "BaseTypes") : NSPersistentContainer(name: "BaseTypes")

        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)         container.loadPersistentStores(completionHandler: { (_, error) in

            guard let error = error as NSError? else { return }

            fatalError("###(#function): Failed to load persistent stores:(error)")

        })

        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

        container.viewContext.transactionAuthor = appTransactionAuthorName

        container.viewContext.automaticallyMergesChangesFromParent = true

        

        do {

            try container.viewContext.setQueryGenerationFrom(.current)

        } catch {

            fatalError("###(#function): Failed to pin viewContext to the current generation:(error)")

        }

        

        NotificationCenter.default.addObserver(

            self, selector: #selector(type(of: self).storeRemoteChange(_:)),

            name: .NSPersistentStoreRemoteChange, object: container.persistentStoreCoordinator)

        return container

    }

    

    func updateContainer() {

        persistentContainer.viewContext.save(with: .saveAll)

        persistentContainer = setupPersistentContainer()

        NotificationCenter.default.post(name: .notificationRefreshUIsAfterChangePS, object: nil)

    }

How to enable/disable cloudkit in runtime.
 
 
Q