首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将Realm数据库传输到appgroups

如何将Realm数据库传输到appgroups
EN

Stack Overflow用户
提问于 2019-09-30 09:29:34
回答 1查看 460关注 0票数 2

嘿,我有一个使用Real来持久化数据的应用程序。我使用默认的领域文件目录来存储应用程序数据,但我希望将文件目录移动到应用程序组,以便创建应用程序扩展名。下面是我更改文件路径的代码

代码语言:javascript
复制
var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.bundle.identifier")!.appendingPathComponent("default.realm")
Realm.Configuration.defaultConfiguration = config

代码完美地更改了文件路径,问题是当我更改路径时,数据会被擦除,因为前一个路径上的数据没有被传输。

其他人也有类似的问题,here,但它非常过时,不起作用

我尝试过这样的传输方法,但都失败了

代码语言:javascript
复制
 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和编程还是相当陌生的,所以请原谅我的笨拙。

EN

回答 1

Stack Overflow用户

发布于 2019-10-01 03:41:14

感谢@Jay的回答,我能够回答我自己的问题。如果其他人需要帮助,下面是我所做的:

代码语言:javascript
复制
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)")
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58160530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档