UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Toggling CloudKit sync in a SwiftUI App life cycle

Forums > SwiftUI

I've been learning about using Core Data with a SwiftUI app I'm working on. I read some great material on using CloudKit and have now implemented this to sync some entities (not all). It's all working great.

I would like to include an option to disable the CloudKit syncing though and I have stumbled somewhat into a brick wall trying to figure how to do this - at least for a SwiftUI App life cycle.

I've come to understand that cloudKitContainerOptions should be set to nil to achieve what I want to do. Setting this in the Persistence.swift file does seem to work. However, this only works when the app loads. If the user toggles it while using the app, there is no change.

I presume this is because I need to refresh the persistence store, but I cannot work out how to do this. This is what I have in my persistence.swift at the moment:


    let container: NSPersistentCloudKitContainer
    @AppStorage("iCloudSync") var iCloudSync = true

    init(inMemory: Bool = false) {

        container = NSPersistentCloudKitContainer(name: “MyApp_2")

        // Support for partial icloud syncing
        let storeDirectory = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first!
        let localUrl = storeDirectory.appendingPathComponent("local.sqlite")
        let local = NSPersistentStoreDescription(url: localUrl)
        local.configuration = "Local"
        let cloudUrl = storeDirectory.appendingPathComponent("cloud.sqlite")
        let cloud = NSPersistentStoreDescription(url: cloudUrl)
        cloud.configuration = "Cloud"
        cloud.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "iCloud.com.myapp.2”)
        container.persistentStoreDescriptions = [local, cloud]
        // support code end

        guard let description = container.persistentStoreDescriptions.first else {
            fatalError("###\(#function): Failed to retrieve a persistent store description.")
        }

        if inMemory {
            container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
        }

        if !iCloudSync { // Check if the sync has been user disabled
            container.persistentStoreDescriptions.last!.cloudKitContainerOptions = nil // Cloud is last at this stage.
        }

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        container.viewContext.automaticallyMergesChangesFromParent = true // Allows us to automatically merge the changes when the silent notifications come in.
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

    }

Could someone point me in the right direction how to refresh things in here?

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.