如何在共享容器中加载新的Core Data文件?

问题描述 投票:0回答:1

我正在使用 Apple 示例代码来使用 NSPersistentCloudKitContainer,并且设置非常简单,如下所示:

lazy var persistentContainer: NSPersistentCloudKitContainer = {

        let container = NSPersistentCloudKitContainer(name: "Name")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {

                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

但现在我需要更改为使用共享容器中的数据库,以便它可以与扩展一起使用。

我尝试将其更改为此代码

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

            // Create a store description for a CloudKit-backed local store
            let storeURL = URL.storeURL(for: "group.com.Name", databaseName: "Name")
            let cloudStoreDescription =
                NSPersistentStoreDescription(url: storeURL)
            cloudStoreDescription.configuration = "Default"

            // Set the container options on the cloud store
            cloudStoreDescription.cloudKitContainerOptions =
                NSPersistentCloudKitContainerOptions(
                    containerIdentifier: "iCloud.com.Name")

            // Update the container's list of store descriptions
            container.persistentStoreDescriptions = [cloudStoreDescription]

            // Load both stores
            container.loadPersistentStores { storeDescription, error in
                guard error == nil else {
                    fatalError("Could not load persistent stores. \(error!)")
                }
            }

            return container
        }()

public extension URL {

    /// Returns a URL for the given app group and database pointing to the sqlite database.
    static func storeURL(for appGroup: String, databaseName: String) -> URL {
        guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
            fatalError("Shared file container could not be created.")
        }

        return fileContainer.appendingPathComponent("\(databaseName).sqlite")
    }
}

但是我收到了这个错误

Fatal error: Could not load persistent stores. Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Unable to find a configuration named 'Default' in the specified managed object model.}: 
core-data cloudkit
1个回答
0
投票

我也有类似的错误。这是我的代码:

@主要 结构 AdMobExampleApp:应用程序 {

@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
let alertManager = AlertManager.shared
let modelContainer: ModelContainer

init() {
    Purchases.logLevel = .debug
    Purchases.configure(withAPIKey: "appl_jsDafSiiISdBhbCfYRUZRzGURCG")

    do {
        //self.modelContainer = try setupModelContainer(for: ModelSchemaV2_0_0.self)
        let databasePath = URL.applicationSupportDirectory.appending(path: "default.store")
        let config = ModelConfiguration(url: databasePath, cloudKitDatabase: .private("iCloud.com.DantesAppInferno.HabitHomies"))
        //let config = ModelConfiguration(cloudKitDatabase: .private("iCloud.kgy.AdMobExample"))
        modelContainer = try ModelContainer(
            for: JournalEntry.self, WeeklyReflection.self, MonthlyReflection.self, Conversation.self, JournalPrompts.self, Habit.self, HabitEntry.self,
            migrationPlan: MigrationPlan.self,
            configurations: ModelConfiguration()
        )
    } catch {
        print("Initialization failed with error: \(error)")
        print("Detailed error info: \(error.localizedDescription)")
        fatalError("Could not initialize ModelContainer")
    }
    HabitService.shared.modelContext = modelContainer.mainContext
    EntriesDataService.shared.modelContext = modelContainer.mainContext
}

var body: some Scene {
    WindowGroup {
        ContentView()
            .environmentObject(alertManager)
            .environmentObject(Coordinator.shared)
            .task {
                //try? Tips.resetDatastore()
                try? Tips.configure([
                    .datastoreLocation(.applicationDefault)
                ])
            }
    }
    .modelContainer(modelContainer)
}

}

这是在 fatalError 崩溃时输出的代码:

CoreData:错误:存储加载失败。 (类型:SQLite,url:file:///var/mobile/Containers/Data/Application/7FE59BD3-ECE3-436C-8242-7703F322E8DB/Library/Application%20Support/default.store),错误=错误域=NSCocoaErrorDomain Code=134060“发生核心数据错误。” UserInfo={NSLocalizedFailureReason=无法在指定的托管对象模型中找到名为“default”的配置。} with userInfo { NSLocalizedFailureReason = "在指定的托管对象模型中找不到名为 'default' 的配置。"; } 加载容器时出现未解决的错误错误域=NSCocoaErrorDomain代码=134060“发生核心数据错误。” UserInfo={NSLocalizedFailureReason=在指定的托管对象模型中找不到名为“default”的配置。} 初始化失败并出现错误:SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer) 详细错误信息:操作无法完成。 (SwiftData.SwiftDataError 错误 1。) AdMobExample/AdMobExampleApp.swift:57:致命错误:无法初始化 ModelContainer

值得注意的是,当我只在模拟器或手机上运行它时,它是有效的,但是一旦我的应用程序的旧版本最初安装在我的手机上,然后将其下载到我的手机上,它就会因该错误而崩溃。我不认为这是一个迁移错误,因为我的迁移计划甚至没有被调用。我在“将迁移”的开头有一个打印声明,但它甚至从未被打印。

© www.soinside.com 2019 - 2024. All rights reserved.