TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

CloudKit keeps syncing after being turned off until the app is relaunched

Forums > Swift

In the following code, I'm saving and syncing objects in Core Data and CloudKit, everything is working fine, once the user creates some objects, the data starts syncing as soon as the user turns the Toggle switch On in the SettingsView. The issue I'm having is that the data continue syncing even after the switch is turned Off until I kill and relaunch the app. After relaunching the app, the data stops syncing.

Any idea what could I do to make sure that the data stops syncing as soon as the toggle switch is turned off?

Again, everything would work fine if the user would kill and relaunch the app right after turning it off, the data stops syncing.

I thought that by calling carViewModel.updateCloudKitContainer() right after turning it off would do the trick since I'm disabling the CloudKit container by making it nil, description.cloudKitContainerOptions = nil but obviously is not enough.

Core Data Manager

    class CoreDataManager{
        // Singleton
        static let instance = CoreDataManager()

        @AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false

        static var preview: CoreDataManager = {
            // Create preview objects
            do {
                try viewContext.save()
            } catch {

            }
            return result
        }()

        lazy var context: NSManagedObjectContext = {
        return container.viewContext
        }()

        lazy var container: NSPersistentContainer = {
        return setupContainer()
        }()

        init(inMemory: Bool = false){
            /// for preview purposes only, remove if no previews are needed.
            if inMemory {
                container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
            }
        }

        func setupContainer()->NSPersistentContainer{
            print("Assgning persistent container... ")
            let 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)

            if iCloudSync{
                let cloudKitContainerIdentifier = "iCloud.com.sitename.myApp"
                let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier)
                description.cloudKitContainerOptions = options
            }else{
                description.cloudKitContainerOptions = nil // turn cloud sync off
            }

            container.loadPersistentStores { (description, error) in
                if let error = error{
                    print("Error loading Core Data. \(error)")
                }
            }
            container.viewContext.automaticallyMergesChangesFromParent = true
            container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

            return container
        }

        func save(){
            do{
                try context.save()
            }catch let error{
                print("Error saving Core Data. \(error.localizedDescription)")
            }
        }
    }

View Model

    class CarViewModel: ObservableObject{

        let manager: CoreDataManager

        @Published var cars: [Car] = []

        init(coreDataManager: CoreDataManager = .instance){
            self.manager = coreDataManager
            loadCars()
        }

        func updateCloudKitContainer(){
            manager.container = manager.setupContainer()
        }

        func addCar(model:String, make:String?){
            // create car
            save()
            loadCars()
        }

        func deleteCar(car: Car){
            // delete car
            save()
            loadCars()
        }

        func loadCars(){
            let request = NSFetchRequest<Car>(entityName: "Car")

            let sort = NSSortDescriptor(keyPath: \Car.model, ascending: true)
            request.sortDescriptors = [sort]
            do{
                cars =  try manager.context.fetch(request)
            }catch let error{
                print("Error fetching businesses. \(error.localizedDescription)")
            }
        }

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

Settings View to Turn ClouldKit ON and OFF

    struct SettingsView: View {
        @ObservedObject var carViewModel:CarViewModel
        @AppStorage(UserDefaults.Keys.iCloudSyncKey) private var iCloudSync = false

        var body: some View {
            VStack{
                Toggle(isOn: $iCloudSync){// turns On and Off sync
                    HStack{
                        Image(systemName: iCloudSync ? "arrow.counterclockwise.icloud" : "lock.icloud")
                            .foregroundColor(Color.fsRed)
                        Text(" iCloud Sync")
                    }
                }
                .tint(Color.fsRed)
                .onChange(of: iCloudSync){ isSwitchOn in
                    if isSwitchOn{
                        iCloudSync = true
                        carViewModel.updateCloudKitContainer()
                    }else{
                        iCloudSync = false // turn Off iCloud Sync
                        carViewModel.updateCloudKitContainer()
                    }
                }
            }
        }
    }

Display Cars View

    struct CarsView: View {
        @ObservedObject var carViewModel:CarViewModel    

        // Capture NOTIFICATION
        var didRemoteChange = NotificationCenter.default.publisher(for: .NSPersistentStoreRemoteChange).receive(on: RunLoop.main)

        var body: some View {

            NavigationView{
                VStack{
                    List { 
                        ForEach(carViewModel.cars) { car in
                            HStack{
                                VStack(alignment:.leading){
                                    Text(car.model ?? "")
                                        .font(.title2)

                                    Text(car.make ?? "")
                                        .font(.callout)
                                }
                            }
                            .swipeActions {
                                Button( role: .destructive){
                                    deleteCar = car
                                    showDeleteActionSheet = true
                                }label:{
                                    Label("Delete", systemImage: "trash.fill")
                                }
                            }
                        }
                    }
                    .navigationBarTitle("Cars")
                    .onAppear{
                        carViewModel.loadCars()
                    }
                    // reload cars on NOTIFICATION
                    .onReceive(self.didRemoteChange){ _ in
                        carViewModel.loadCars()
                    }
                }
            }
        }   
    }

3      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.