swifticloudnspersistentcloudkitcontainer

Toggle iCloud sync during runtime


I have a SwiftUI App, where the user can buy with in-app purchases some premium features. One of this features is iCloud sync over more devices. I am using CoreData to save users data. My persistent container:

lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "store name")
        let description: NSPersistentStoreDescription? = container.persistentStoreDescriptions.first
        let remoteChangeKey: String = "NSPersistentStoreRemoteChangeNotificationOptionKey"
        if(description != nil) {
            description!.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
            description!.setOption(true as NSNumber, forKey: remoteChangeKey)
        }
        
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

My question is how can I toggle on/off cloud sync when the user buy a subscription. I don't want hat the user have to restart the app. I also want that the user can toggle this setting in the in-app settings.


Solution

  • Declare your variable as a NSPersistentContainer instead of NSPersistentCloudKitContainer. On launch, if the user has cloud sync, load the cloud kit persistent container, otherwise load the non-cloud kit one.

    When the switch is toggled, reload the container, following the same rules. To reload the container, I would add the property to a manager object, in which I would add some methods that reload the the container depending on the user's settings.