【问题标题】:How to solve Core Data error: Attempt to add read-only file at path when trying to access Core Data container in the app extension today widget?如何解决 Core Data 错误:尝试在今日应用扩展小部件中访问 Core Data 容器时尝试在路径中添加只读文件?
【发布时间】:2017-10-09 09:59:22
【问题描述】:

我正在尝试使用今日扩展小部件中的 Core Data 访问数据库。

创建核心数据容器的函数是这样的:

func createContainer(completion: @escaping (NSPersistentContainer) -> ()) {
    let applicationGroupIdentifier = "group.com.name.exampleApp.sharedContainer"

    guard let newURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: applicationGroupIdentifier)
        else { fatalError("Could not create persistent store URL") }

    let persistentStoreDescription = NSPersistentStoreDescription()

    persistentStoreDescription.url = newURL

    let container = NSPersistentContainer(name: "ContainerName")

    container.persistentStoreDescriptions = [persistentStoreDescription]

    container.loadPersistentStores { (_, error) in
        guard error == nil else { fatalError("Failed to load store:\(String(describing: error))") }
        DispatchQueue.main.async { completion(container) }
    }
}

但是,我收到以下错误:

CoreData:错误:尝试在路径中添加只读文件 file:///private/var/mobile/Containers/Shared/AppGroup/C9324B65B-265C-4264-95DE-B5AC5C9DAFD0/ 读/写。改为只读方式添加。这将是一个硬错误 未来;您必须指定 NSReadOnlyPersistentStoreOption。

如果我像这样指定 NSReadOnlyPersistentStoreOption:

persistentStoreDescription.isReadOnly = false

我得到错误:

加载存储失败:可选(错误域=NSCocoaErrorDomain 代码=513 "无法保存文件,因为您没有权限。"):

可能是什么原因和解决方法?

【问题讨论】:

    标签: ios core-data ios10


    【解决方案1】:
    1. 在扩展的 info.plist 集中:NSExtension --> NSExtensionAttributes --> RequestOpenAccess --> YES
    2. 在设备集的设置中:您的应用 -->(扩展类型 - 例如:键盘)--> 允许完全访问

    【讨论】:

      【解决方案2】:

      遇到同样的问题,通过添加解决了

      let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.identifier")!
      let url = directory.appendingPathComponent("MyDatabaseName.sqlite")
      

      CoreData 可能试图打开 base 文件夹作为其 sqlite 数据库,但效果并不好。

      添加 isReadOnly 也不允许 CoreData 重新调整文件夹的用途 :)

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

      【讨论】:

      • 我使用与您相同的来源,但使用不同的扩展名 (unwantedCommunicationExtension)。当我尝试从扩展本身写入时,我仍然遇到同样的错误
      • @tink So file:///private/var/mobile/Containers/Shared/AppGroup/C9324B65B-265C-4264-95DE-B5AC5C9DAFD0/: 是你的错误的一部分吗?
      • 原来每个扩展都有不同的隐私捕获。我正在使用的那个(Unwanted Comm. Reporting)不允许从扩展部分写任何东西,甚至 NSUserDefaults .. 我尝试了很多事情,在某些时候我也遇到了你提到的错误。我不记得我做了什么来修复它。对不起!
      • @tink 一直发生在我身上。 :) 因此,尽管无法做到,但您还是要写它,还是您只是避免这样做?这听起来是个有趣的故事。
      • 不值得一试。即使我绕过一些方法,他们也会拒绝该应用程序。所以我完全改变了我的后端。我想将所有报告的消息存储在核心数据中,并在应用程序中显示报告历史记录,但现在我将我的 UUID 传递给后端并调用以在应用程序中检索它。警告:您必须先打开应用程序至少一次,然后再进行其他操作。 (prolly 让用户接受条款,同时在后台存储您需要的用户默认值)底线:您可以将您想要的任何内容从您的应用程序传递给扩展程序,但反之则不行。
      猜你喜欢
      • 1970-01-01
      • 2016-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多