领域 - 将包含初始数据的文件添加到项目中(iOS / Swift) [英] Realm - Add file with initial data to project (iOS/Swift)

查看:99
本文介绍了领域 - 将包含初始数据的文件添加到项目中(iOS / Swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用swift开发iOS应用程序,并选择Realm作为它的数据库解决方案。我使用realm docs中的write / add函数在AppDelegate中编写了默认数据,它工作得很好。所以在第一次启动后,我有一个带有初始数据的* .realm文件。在Realm文档中,我找到了一个名为将一个域与一个应用程序捆绑的部分,我将* .realm文件添加到项目中并在编写时构建阶段。

I'm developing an application for iOS using swift and chose Realm as a database solution for it. I wrote default data in AppDelegate using write/add function from realm docs and it works just fine. So after first launch I have a *.realm file with my initial data. In Realm documentation I found a section called "Bundling a Realm with an App", I add my *.realm file to project and to Build Phases as it written.

我无法理解下一步应该做什么(和部分关于压缩* .realm文件)。我试图理解来自迁移示例但我不太了解Obj-C。

And I can't understand what I should do next (and part about compressing a *.realm file). I've tried to understand a code from Migration Example but I don't know Obj-C well.

请尽可能明确地将* .realm文件与初始数据一起添加到swift ios项目并加载第一次启动时,这些数据到Realm数据库。

Please give as clear steps as you can to add *.realm file with initial data to swift ios project and load this data to the Realm db with the first launch.

推荐答案

实现此功能 openRealm 在AppDelegate中并在其中调用

Implement this function openRealm in AppDelegate and call it in

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    ...
    openRealm() 

    return true
 }

func openRealm() {

    let defaultRealmPath = Realm.defaultPath
    let bundleReamPath = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("default.realm")

    if !NSFileManager.defaultManager().fileExistsAtPath(defaultRealmPath) {
        NSFileManager.defaultManager().copyItemAtPath(bundleReamPath!, toPath: defaultRealmPath, error: nil)
    }
}

它会将您捆绑在应用程序中的领域文件复制到默认领域路径(如果它尚不存在)。之后您通常使用Realm,就像之前使用的那样。

It will copy your realm file that you bundled in the app to the default realm path, if it doesn't exist already. After that you use Realm normally like you used before.

还有你在 Swift

在Swift中3.0.1你可能更喜欢这个:

In Swift 3.0.1 you may prefer this:

    let defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
    let bundleRealmPath = Bundle.main.url(forResource: "seeds", withExtension: "realm")

    if !FileManager.default.fileExists(atPath: defaultRealmPath.absoluteString) {
        do {
            try FileManager.default.copyItem(at: bundleRealmPath!, to: defaultRealmPath)
        } catch let error {
            print("error copying seeds: \(error)")
        }
    }

(但请注意选项)

这篇关于领域 - 将包含初始数据的文件添加到项目中(iOS / Swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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