如何捆绑领域文件 [英] 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.
// 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代码= 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,底层=非领域文件,NSLocalizedDescription =无法打开路径为'/var/mobile/Containers/Data/Application/B4D487F8-5AEC-4906-B989-7DB953095A35/Documents/default.realm'的领域:不是领域文件.}
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 !
推荐答案
看来,您的行try Realm().writeCopy(toFile: destination)
基本上打开了默认领域文件,但是没有解密它所需的密钥(我假设您已经加密了)在尝试编写压缩副本之前,请先点击此处.
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抱怨无法打开该文件,因为它不是Realm文件(不是,它是加密版本).
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).
使用适当的加密密钥(try Realm(configuration: config)
或类似的加密密钥)打开Realm,然后然后尝试编写副本.
Open the Realm using the appropriate encryption key (try Realm(configuration: config)
or similar) and then try writing a copy.
这篇关于如何捆绑领域文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!