iOS   发布时间:2022-05-04  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 如何使用swift 3 xcode 8在核心数据中预加载数据库大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

概述

我有一个包含数据的数据库,我想在应用程序中预加载它.在 swift 3之前它可以工作,我已经按照本教程: http://www.appcoda.com/core-data-preload-sqlite-database/但是如何为swift 3加载相同的数据库?在介绍NSPersistentContainer时如何加载我项目中的.sqlite文件? 实际上,在swift 3中更改了创建数据库的默认
我有一个包含数据的数据库,我想在应用程序中预加载它.在 swift 3之前它可以工作,我已经按照本教程: http://www.appcoda.com/core-data-preload-sqlite-database/但是如何为swift 3加载相同的数据库?在介绍NSPersistentContainer时如何加载我项目中的.sqlite文件

解决方法

实际上,在swift 3中更改了创建数据库认路径.所以现在代码看起来像:

func preloadDBData() {
    let sqlitePath = Bundle.main.path(forresource: "MyDB",ofType: "sqlite")
    let sqlitePath_shm = Bundle.main.path(forresource: "MyDB",ofType: "sqlite-shm")
    let sqlitePath_wal = Bundle.main.path(forresource: "MyDB",ofType: "sqlite-wal")

    let URL1 = URL(fileURLWithPath: sqlitePath!)
    let URL2 = URL(fileURLWithPath: sqlitePath_shm!)
    let URL3 = URL(fileURLWithPath: sqlitePath_wal!)
    let URL4 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite")
    let URL5 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite-shm")
    let URL6 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite-wal")

    if !FileManager.default.fileExists(atPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite") {
        // Copy 3 files
        do {
            try FileManager.default.copyItem(at: URL1,to: URL4)
            try FileManager.default.copyItem(at: URL2,to: URL5)
            try FileManager.default.copyItem(at: URL3,to: URL6)

            print("=======================")
            print("FILES COPIED")
            print("=======================")

        } catch {
            print("=======================")
            print("ERROR IN COPY OPERATION")
            print("=======================")
        }
    } else {
        print("=======================")
        print("FILES EXIST")
        print("=======================")
    }
}

现在你可以从AppDelegate的didFinishLaunchWithOptions方法调用这个方法,这将预加载我们放在应用程序中的数据库.

大佬总结

以上是大佬教程为你收集整理的ios – 如何使用swift 3 xcode 8在核心数据中预加载数据库全部内容,希望文章能够帮你解决ios – 如何使用swift 3 xcode 8在核心数据中预加载数据库所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。