ios - 如何将 Realm 数据库转移到应用程序组
问题描述
嘿,我有一个使用 Real 来持久化数据的应用程序。我使用默认领域文件目录来存储应用程序数据,但我想将文件目录移动到应用程序组以创建应用程序扩展。这是我更改文件路径的代码
var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.bundle.identifier")!.appendingPathComponent("default.realm")
Realm.Configuration.defaultConfiguration = config
该代码完美地更改了文件路径,问题是当我更改路径时数据被擦除,因为前一个路径的数据没有被传输。
其他人在这里也有类似的问题,但它已经过时并且没有用
我试过这样的转移方法,但都失败了
migrateData(){
let fileManager = FileManager.default
//Cache original realm path (documents directory)
let originalDefaultRealmPath = realm.configuration.fileURL?.absoluteString
//Generate new realm path based on app group
let appGroupURL: NSURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.groupIndentifier")! as NSURL
let realmPath = appGroupURL.path!.appending("default.realm")
//Moves the realm to the new location if it hasn't been done previously
if (fileManager.fileExists(atPath: originalDefaultRealmPath!) && !fileManager.fileExists(atPath: realmPath)) {
do{
try fileManager.moveItem(atPath: originalDefaultRealmPath!, toPath: realmPath)
}
catch{
print("error")
}
}
let config = Realm.Configuration(fileURL: appGroupURL.absoluteURL)
//Set the realm path to the new directory
Realm.Configuration.defaultConfiguration = config
}
提前感谢您的帮助!总的来说,我对 Swift 和编程还很陌生,所以如果我一无所知,请原谅。
解决方案
感谢@Jay 的回答,我能够回答我自己的问题。如果其他人需要帮助,这就是我所做的:
let fileManager = FileManager.default
let originalPath = Realm.Configuration.defaultConfiguration.fileURL!
let appGroupURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.bundle.identifier")!.appendingPathComponent("default.realm")
do{
try fileManager.replaceItemAt(appGroupURL, withItemAt: originalPath )
}
catch{
print("Error info: \(error)")
}
推荐阅读
- bitbucket - 在 Bitbucket 上绕过分支权限:拉取请求需要批准,但无论如何都要合并?
- apache-spark - 如何在旧版 Spark Streaming 中使用 foreachRDD
- php - 带有分类下拉列表的 WPBakery Page Builder 不起作用
- google-apps-script - 您的脚本 Drive Migrator 最近未能成功完成
- excel - 如何使用 CommandBars 将从 excel 复制的图表定位到 powerpoint?
- mysql - SQL - 在大表上选择最后一行的更快且不那么贪婪的方法是什么?
- python - 如何重新定义 MagicMock __str__ 方法?
- java - Spring-boot JPA,使用 LIKE 和 NULL 字段查询
- java - 如何通过“类”或“跨类”查找元素?
- ios - 使用子查询进行领域计算和排序