SwiftUI: ICloud Documents alongside CloudKit

206 Views Asked by At

I'm working on an app that uses both ICloud Documents and the new CloudKit. Both services are active on ICloud section under "Signing & Capabilities".

Services and Containers for ICloud in XCode

Because CloudKit is used in the whole app, I'll instantiate in the appDelegate like this

 lazy var persistentContainer: NSPersistentCloudKitContainer = {
        let container = NSPersistentCloudKitContainer(name: "MyTestApp")

        container.loadPersistentStores(completionHandler: { _, error in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        container.viewContext.automaticallyMergesChangesFromParent = true

        return container
    }()

and made available via

struct MyTestApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
                .environment(\.managedObjectContext, appDelegate.persistentContainer.viewContext)
        }
    }
}

In a view within the app I'm trying to access the data from iCloud Documents so what I'm doing is:

struct TestReadICDView: View {
    private let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: "iCloud.it.mytestapp.oldcontainer")?.appendingPathComponent("MyTestApp.sqlite")

    init() {
        guard let modelURL = Bundle.main.url(forResource: "MyTestApp", withExtension: "momd") else {
            fatalError("Error loading model from bundle")
        }

        guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
            fatalError("Error initializing mom from: \(modelURL)")
        }

        let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)

        let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

        context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy

        context.persistentStoreCoordinator = psc

        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: iCloudDocumentsURL, options: nil)
            let fetchRequest: NSFetchRequest<Nota> = Nota.fetchRequest()
            let data = try context.fetch(fetchRequest)
            print("count: \(data.count)")
        } catch {
            fatalError("Error adding store: \(error)")
        }
    }

    var body: some View {
        Text("Hello World!")
    }
}

But every time I enter the view I got:

Thread 1: "executeFetchRequest:error: A fetch request must have an entity."

But the entity is specified in the NSFetchRequest.

I cannot understand why

0

There are 0 best solutions below