ios 键盘扩展中的核心数据

Coredata in ios keyboard extension

我阅读了下面的 github 页面,并使用代码在我的 ios 键盘扩展和应用程序之间共享 coredata

https://github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups

代码在模拟器上工作正常,但它不工作但addPersistentStore在真实设备上不工作:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
    // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
    // Create the coordinator and store
    var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)

    let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:"group.testKeyboard.asanpardakht.ir")!

    let url = directory.appendingPathComponent("AsanPardakhtSharedData.sqlite")

    do {
        try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
    } catch var error as NSError {
        coordinator = nil
        NSLog("Unresolved error \(error), \(error.userInfo)")
        abort()
    } catch {
        fatalError()
    }
    print("\(String(describing: coordinator?.persistentStores))")
    return coordinator
}()

我遇到以下错误:

NSError domain: "NSCocoaErrorDomain" - code: 512

"reason" : "Failed to create file; code = 1"

我尝试在我的 info.plist 文件中将 RequestOpenAccess 设置为 YES,但它仍然无法正常工作。有人知道这个问题吗?

我发现下面的 post 也适用于键盘扩展:

https://github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups

唯一的问题是,对于键盘扩展,我们还应该将 info.plist 处的 RequestOpenAccess 设置为 YES

当在键盘设置中将其设置为 YES 时,会出现 Full Access 的选项,我们应该将其打开,然后代码也可以在真实设备上运行。

开发人员应确保在调用任务中的方法之前要求用户将选项打开。