仅一台设备出错:open() 失败:不允许操作路径:default.realm.lock

Error only one device : open() failed: Operation not permitted Path: default.realm.lock

static func 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 文件是一个仅由领域使用的幕后文件。在使用捆绑领域时,您永远不需要直接使用该文件或将其捆绑。所有需要的领域文件本身,拖入 XCode 项目。

以下是访问名为 MyBundledData.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)

这应该是所有需要的

尝试在父目录中添加 NSFileProtectionNone 让境界=尝试!境界()

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

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