如何捆绑领域文件

时间:2018-03-15 10:54:41

标签: ios swift realm

关于如何捆绑域文件的realm documentation之后。我已成功将所有必要的数据加载到我的加密文件中,但我似乎无法压缩文件并将其移至其他位置。

代码

    // AppDelegate
    fileprivate func compactRealm() {
        if let realmPath = Realm.Configuration.defaultConfiguration.fileURL {
            let destination = realmPath.deletingLastPathComponent().appendingPathComponent("compact.realm")
            if FileManager.default.fileExists(atPath: realmPath.path) {
                do {
//                    let encryption = Constants.key.data(using: String.Encoding.utf8)
                    try Realm().writeCopy(toFile: destination)
                    print("File normally compressed !")

                } catch {
                    fatalError(error.localizedDescription)
                }
            } else {
                print("Realm file does not exist")
//                fatalError()
            }

        }

    } 

结果

  

错误域名= io.realm代码= 2"无法在路径' / var / mobile / Containers / Data / Application / B4D487F8-5AEC-4906-B989-7DB953095A35 / Documents /中打开域default.realm':不是Realm文件。" UserInfo = {错误代码= 2,NSFilePath = / var / mobile / Containers / Data / Application / B4D487F8-5AEC-4906-B989-7DB953095A35 / Documents / default.realm,Underlying =不是Realm文件,NSLocalizedDescription =无法打开路径领域' /var/mobile/Containers/Data/Application/B4D487F8-5AEC-4906-B989-7DB953095A35/Documents/default.realm' ;:不是领域文件。}

我已经检查过:领域文件确实存在!

顺便说一句,我已尝试使用未加密的文件使用相同的代码并且它有效,所以我不知道它不能使用加密的域文件!

1 个答案:

答案 0 :(得分:0)

看来您的行try Realm().writeCopy(toFile: destination)基本上打开了默认域文件,但没有解密它所需的密钥(我假设您在尝试编写压缩副本之前已经将其加密了)。 / p>

Realm抱怨该文件无法打开,因为它不是Realm文件(不是,它是乱码版本)。

使用适当的加密密钥(try Realm(configuration: config)或类似的)打开领域,然后然后尝试写一份副本。

来源

Realm Docs - Encryption

Realm Docs - Compacting Realms