我正在关注 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)
或类似方法),然后然后尝试写入副本。
来源
关于ios - 如何捆绑 Realm 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49297592/