FREE TRIAL: Accelerate your app development career with 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: "”)
        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?


Hacking with Swift is sponsored by Essential Developer

SPONSORED From August 2nd to 8th you can 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!

Save your spot now

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.