首页 > 解决方案 > 如何将 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 和编程还很陌生,所以如果我一无所知,请原谅。

标签: iosswiftdatabaserealmios-app-group

解决方案


感谢@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)")
    }

推荐阅读