Search code examples
iosswiftrealm

How to bundle a realm file


I'm following the realm documentation on how to bundle a realm file. I've successfully loaded all necessary data into my encrypted file, but I can't seem to compact the file and move it elsewhere.

Code

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

        }

    } 

Result

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.}

I've checked : the realm file does exist !.

BTW, I've tried the same code with unencrypted file and it worked, so I don't know it wouldn't work with an encrypted realm file !


Solution

  • It appears that your line try Realm().writeCopy(toFile: destination) basically opens the default realm file, but without the key needed to decrypt it (I'm assuming you've already encrypted it here before attempting to write a compact copy).

    Realm complains that the file can't be opened because it's not a Realm file (it's not, it's a scrambled version of it).

    Open the Realm using the appropriate encryption key (try Realm(configuration: config) or similar) and then try writing a copy.

    Sources

    Realm Docs - Encryption

    Realm Docs - Compacting Realms