How to transfer Realm database to appgroups

浪尽此生 提交于 2021-02-11 08:27:28

问题


Hey I have an app that uses Real to persist data. I used the default realm file directory to store the apps data but I would like to move the file directory to app groups in order to create app extensions. Heres my code for changing the file path

var config = Realm.Configuration()
config.fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.bundle.identifier")!.appendingPathComponent("default.realm")
Realm.Configuration.defaultConfiguration = config

The code changes the file path perfectly, the problem is that the data gets wiped when I change the path, since the data at the previous path isn't being transferred.

Someone else had a similar question here, but it's very outdated and didn't work

I've tried methods of transferring it such as this, but all as failed

 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
}

Thanks in advance for help! I'm still fairly new to Swift and programming in general so excuse me if I'm being clueless.


回答1:


Thanks to @Jay's answer, I was able to answer my own question. In case anyone else needs help, heres what I did:

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)")
    }


来源:https://stackoverflow.com/questions/58160530/how-to-transfer-realm-database-to-appgroups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!