Understanding Syncing between Core Data and CloudKit Public Database using NSPersistantCloudKitContainer

Can someone please give me an overview of how sync works between Core Data and the public CloudKit database when using the NSPersistentCloudKitContainer and please point out my misunderstandings based on what I describe below?

In the following code, I'm successfully connecting to the public database in CloudKit using the NSPersistentCloudKitContainer. Below is how I have Core Data and CloudKit set up for your reference. In CloudKit I have a set of PublicIconImage that I created manually via the CloudKit Console. I intend to be able to download all images from the public database at the app launch to the local device and manage them via Core Data to minimize server requests, which works but only if the user is logged in.

This is the behavior I see:

When the app launches, all the CloudKit images get mirrored to Core Data and displayed on the screen but only if the user is logged in with the Apple ID, otherwise nothing gets mirrored.

What I was expecting:

I was under the impression that when connecting to the public database in CloudKit you didn't need to be logged in to read data. Now, if the user is logged in on the first launch, all data is successfully mirrored to Core Data, but then if the user logs off, all data previously mirrored gets removed from Core Data, and I was under the impression that since Core Data had the data already locally, it would keep the data already downloaded regardless if it can connect to CloudKit or not.

What am I doing wrong?

Core Data Model:

Entity: PublicIconImage Attributes: id (UUID), imageName (String), image (Binary Data).

CloudKit Schema in Public Database:

Record: CD_PublicIconImage Fields: CD_id (String), CD_imageName (String), CD_image (Bytes).

Core Data Manager

class CoreDataManager: ObservableObject{ // Singleton static let instance = CoreDataManager() private let queue = DispatchQueue(label: "CoreDataManagerQueue")

private var iCloudSync = true

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

lazy var container: NSPersistentContainer = {
   return setupContainer()
}()
    
func updateCloudKitContainer() {
    queue.sync {
        container = setupContainer()
    }
}

func setupContainer()->NSPersistentContainer{
    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)

    let cloudKitContainerIdentifier = "iCloud.com.example.PublicDatabaseTest"
         
    let options = NSPersistentCloudKitContainerOptions(containerIdentifier: cloudKitContainerIdentifier)
    description.cloudKitContainerOptions = options
          
    description.cloudKitContainerOptions?.databaseScope = .public // Specify Public Database
    
    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

class PublicIconImageViewModel: ObservableObject { let manager: CoreDataManager

@Published var publicIcons: [PublicIconImage] = []

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

func loadPublicIcons() {
    let request = NSFetchRequest<PublicIconImage>(entityName: "PublicIconImage")
    
    let sort = NSSortDescriptor(keyPath: \PublicIconImage.imageName, ascending: true)
    request.sortDescriptors = [sort]

    do {
        publicIcons = try manager.context.fetch(request)
    } catch let error {
        print("Error fetching PublicIconImages. \(error.localizedDescription)")
    }
}

}

SwiftUI View

struct ContentView: View { @EnvironmentObject private var publicIconViewModel: PublicIconImageViewModel

var body: some View {
    VStack {
        List {
            ForEach(publicIconViewModel.publicIcons) { icon in
                HStack{
                    Text(icon.imageName ?? "unknown name")
                    Spacer()
                    if let iconImageData = icon.image, let uiImage = UIImage(data: iconImageData) {
                        Image(uiImage: uiImage)
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 35, height: 35)
                    }
                }
            }
        }
        .onAppear {
            // give some time to get the images downlaoded
            DispatchQueue.main.asyncAfter(deadline: .now() + 5){
                publicIconViewModel.loadPublicIcons()
            }
        }
    }
    .padding()
}

}

Understanding Syncing between Core Data and CloudKit Public Database using NSPersistantCloudKitContainer
 
 
Q