如何将Realm数据库传输到应用程序组 [英] How to transfer Realm database to appgroups

查看:64
本文介绍了如何将Realm数据库传输到应用程序组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我有一个使用Real来保存数据的应用程序.我使用默认的领域文件目录存储应用程序数据,但我想将文件目录移至应用程序组以创建应用程序扩展名.这是我更改文件路径的代码

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.

其他人在此处a>,但是它已经过时了,没有用

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
}

在此先感谢您的帮助!一般来说,我对Swift和编程还是很陌生,所以如果我一无所知,请原谅.

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

推荐答案

由于@Jay的回答,我得以回答自己的问题.万一其他人需要帮助,这是我的工作:

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

这篇关于如何将Realm数据库传输到应用程序组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆