加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 如何使用swift 3 xcode 8在核心数据中预加载数据库

发布时间:2020-12-14 18:12:30 所属栏目:百科 来源:网络整理
导读:我有一个包含数据的数据库,我想在应用程序中预加载它.在 swift 3之前它可以工作,我已经按照本教程: http://www.appcoda.com/core-data-preload-sqlite-database/但是如何为swift 3加载相同的数据库?在介绍NSPersistentContainer时如何加载我项目中的.sqlit
我有一个包含数据的数据库,我想在应用程序中预加载它.在 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方法调用这个方法,这将预加载我们放在应用程序中的数据库.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读