如何在swift4.2中将领域文件与我的应用捆绑在一起?

时间:2019-01-28 21:09:11

标签: ios swift xcode realm

我想在设备上的应用程序的第一顿午餐时显示持久性数据,以便用户可以看到它,并且我将领域用作我的数据库。

我在模拟器上用数据填充文件后被欺骗,现在需要将数据文件与应用程序合并或捆绑在一起。 现在我将default.realm文件复制到dcouments 我从AppDelegate的stackoverflow复制了一些相关代码以捆绑它,但是失败了!

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    openRealm() //2
    print(Realm.Configuration.defaultConfiguration.fileURL) //3
    return true
}

//1
func openRealm() {
    let bundlePath = Bundle.main.path(forResource: "default", ofType: "realm")!
    let defaultPath = Realm.Configuration.defaultConfiguration.fileURL!.path
    let fileManager = FileManager.default

    // Only need to copy the prepopulated `.realm` file if it doesn't exist yet
    if !fileManager.fileExists(atPath: defaultPath){
        print("use pre-populated database")
        do {
            try fileManager.copyItem(atPath: bundlePath, toPath: defaultPath)
            print("Copied")
        } catch {
            print(error)
        }
    }

} //f

当我构建应用程序时,它总是崩溃,并且Xcode告诉我该值为零

  

线程1:致命错误:展开包装时意外发现nil   可选值

1 个答案:

答案 0 :(得分:0)

确保文件的“目标成员身份”正确

Target Maembership

并且该文件包含在“构建阶段/复制捆绑包资源”中

Copy bundle resource

是的,我在上浪费了时间