【问题标题】:Error only one device : open() failed: Operation not permitted Path: default.realm.lock只有一台设备出错:open() 失败:不允许操作路径:default.realm.lock
【发布时间】:2021-08-11 05:07:20
【问题描述】:

静态函数 realmConfig() -> Realm.Configuration {

    var config = Realm.Configuration(schemaVersion: 6, migrationBlock: { (migration, oldSchemaVersion) in
        /// Migration block. Useful when you upgrade the schema version.
        
    })
    
    config.fileURL = Bundle.main.url(forResource: "default", withExtension: "realm")!
    print(config.fileURL)
    let folderPath = config.fileURL!.deletingLastPathComponent().path
    let lockPath = Bundle.main.url(forResource: "default.realm", withExtension: "lock")!.path
    do {
        try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.none],ofItemAtPath: folderPath)
        try FileManager.default.setAttributes([FileAttributeKey.protectionKey: FileProtectionType.none],ofItemAtPath: lockPath)
    } catch {
        fatalError("Realm initialization failed, Error:\(error)")
    }
    
    return config
}

private static func realmInstance() -> Realm {
    do {
        let newRealm = try Realm(configuration: realmConfig())
        return newRealm
    } catch {
        print(error)
        fatalError("Unable to create an instance of Realm")
    }
}

}

【问题讨论】:

  • 等等,你为什么要打开.lock文件?
  • 如果数据被加密,则无法读取文件。
  • 这个问题有点不清楚。如果您已将 Realm 添加到您的 App Bundle 中,则无需涉及 Filemanager(如您问题中的代码所示)。此外,您永远不需要对 .lock 文件做任何事情,如果 Realm 是您的应用程序包的一部分,那么无论如何也不会有 .lock 文件。访问捆绑的 Realm 所需要做的就是使用问题 config.fileURL = Bundle.main... 中的代码行。有什么我们不明白的吗?你想做什么?
  • @aheze 我不想打开所有锁定文件。我正在尝试使用我的捆绑包中的特定 URL 从配置创建一个 Realm 实例。
  • @Jay 文件管理器是授予父文件夹权限.. 我所做的是复制之前生成的所有文件并将它们添加到 iOS 应用程序项目并尝试访问它们。奇怪的是它只在模拟器上工作。我试图删除 .lock 文件相同的结果

标签: ios swift mongodb realm realm-mobile-platform


【解决方案1】:

领域 .lock 文件是仅由领域使用的底层文件。使用捆绑领域时,您永远不需要直接使用该文件或捆绑它。将领域文件本身所需的所有内容拖到 XCode 项目中。

以下是访问名为 MyBundledData.realm 的捆绑 Realm 的方法:

let config = Realm.Configuration(
    // Get the URL to the bundled file
    fileURL: Bundle.main.url(forResource: "MyBundledData", withExtension: "realm"),
    // Open the file in read-only mode as application bundles are not writeable
    readOnly: true)

// Open the Realm with the configuration
let realm = try! Realm(configuration: config)

这应该是所有需要的

【讨论】:

  • 奇怪的是,当我添加 readonly = true 时它起作用了!
【解决方案2】:

尝试在父目录上添加 NSFileProtectionNone 让领域=尝试!领域()

// 获取我们的 Realm 文件的父目录 let folderPath = realm.configuration.fileURL!.deletingLastPathComponent().path

// 禁用此目录的文件保护 尝试! FileManager.default.setAttributes([FileAttributeKey(rawValue: NSFileProtectionKey): NSFileProtectionNone], ofItemAtPath: 文件夹路径)

【讨论】:

    猜你喜欢
    • 2012-08-12
    • 2020-01-29
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2019-01-25
    • 2023-01-27
    • 1970-01-01
    相关资源
    最近更新 更多