I'm trying to give the user the ability to decide whether they want to sync to CloudKit
or not by turning On or Off a Switch
located somewhere in the app settings screen but I'm not sure how to do it in SwiftUI
.
The following code successfully stops the sync to CloudKit
by setting the cloud kit container options to nil description.cloudKitContainerOptions = nil
.
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)
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)")
}
}
}
What I ultimately want is to be able to control the syncing process with an @AppStore
property or some sort of property, something like this...
class CoreDataManager{
@AppStorage("iCloudSync") private var iCloudSync = false
//missing code...
init(){
if !iCloudSync{
description.cloudKitContainerOptions = nil
}
}
//missing code...
}
But I'm facing a couple of issues, one, I'm getting an error when using the iCloudSync
wrapper variable and the second one and the most difficult for me to solve is
the fact that I need to make the persistent storage reload when the switch changes from On to Off of vise-versa.
Any idea how can I structure my code so I can control the syncing process and be able to reload the persistent storage when the switch changes?
By the way and just for reference, here is how I'm using the CoreDataManager
class in my 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()
}
}