4

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.

thanks

Leahpar
  • 583
  • 1
  • 4
  • 12

1 Answers1

4

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.

EmilioPelaez
  • 18,758
  • 6
  • 46
  • 50
  • Something like that? ` lazy var ..... let container = self.iapManager.isPremiumVersion ? NSPersistentCloudKitContainer(name: "store name") : NSPersistentContainer(name: "store name") .... ` But haw can I reload the container? – Leahpar Feb 04 '20 at 18:14
  • I have been able to find a solution: https://stackoverflow.com/questions/65355720/coredatacloudkit-on-off-icloud-sync-toggle – Kai Zheng Dec 18 '20 at 16:11