ios - 如何捆绑 Realm 文件

标签 ios swift realm

我正在关注 realm documentation关于如何捆绑 Realm 文件。我已成功将所有必要的数据加载到加密文件中,但我似乎无法压缩该文件并将其移动到其他地方。

代码

    // 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()
            }

        }

    } 

结果

Error Domain=io.realm Code=2 "Unable to open a realm at path '/var/mobile/Containers/Data/Application/B4D487F8-5AEC-4906-B989-7DB953095A35/Documents/default.realm': Not a Realm file." UserInfo={Error Code=2, NSFilePath=/var/mobile/Containers/Data/Application/B4D487F8-5AEC-4906-B989-7DB953095A35/Documents/default.realm, Underlying=Not a Realm file, NSLocalizedDescription=Unable to open a realm at path '/var/mobile/Containers/Data/Application/B4D487F8-5AEC-4906-B989-7DB953095A35/Documents/default.realm': Not a Realm file.}

我已经检查过: Realm 文件确实存在!。

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

最佳答案

看来您的行 try Realm().writeCopy(toFile: destination) 基本上打开了默认的 Realm 文件,但没有解密它所需的 key (我假设您已经在尝试写入压缩副本之前,请在此处对其进行加密)。

Realm 提示该文件无法打开,因为它不是 Realm 文件(不是,它是它的加扰版本)。

使用适当的加密 key 打开 Realm(尝试 Realm(configuration: config) 或类似方法),然后然后尝试写入副本。

来源

Realm Docs - Encryption

Realm Docs - Compacting Realms

关于ios - 如何捆绑 Realm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49297592/

相关文章:

ios - Amazon Cloudfront 可以流式传输到 iOS 设备吗

iphone - 在不需要的 View 中触发替代景观

ios - 使用 Simperium 构建 iOS 应用程序时出现链接器错误

ios - Realm Swift 仅在本地使用,但它仍会尝试在线连接

swift - Swift 3.0.2 中的一对多

swift - 使用 Realm 保存 viewController 之间的模型状态 - 它会破坏关系

ios - 在 NSSortDescriptor 中排序(今天之前或之后)

swift - SceneKit euler 在旋转期间角度奇怪的值

Swift 安全区布局指南和视觉格式语言

json - 如何使用 AlamofireObjectMapper 将 JSON 字典添加到 Realm