我正在关注如何捆绑领域文件的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()
}
}
}
结果
错误Domain = io.realm Code = 2“无法在路径上打开领域'/var/mobile/Containers/Data/Application/B4D487F8-5AEC-4906-B989-7DB953095A35/Documents/default.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':不是领域文件 . }
我检查过:领域文件确实存在!
顺便说一下,我用未加密的文件尝试了相同的代码并且它有效,所以我不知道它不适用于加密的realm文件!
1 回答
看来您的行
try Realm().writeCopy(toFile: destination)
基本上打开了默认的域文件,但是没有解密它所需的密钥(在尝试编写压缩副本之前,我已经在这里加密了它) .Realm抱怨该文件无法打开,因为它不是Realm文件(它不是,它是一个混乱的版本) .
使用适当的加密密钥(
try Realm(configuration: config)
或类似)打开领域,然后尝试编写副本 .来源
Realm Docs - Encryption
Realm Docs - Compacting Realms