How to pre load database in core data using swift 3 xcode 8

徘徊边缘 提交于 2020-01-02 05:36:11

问题


I have a database with data and I want to preload that in application. Before swift 3 it works and I have followed this tutorial : http://www.appcoda.com/core-data-preload-sqlite-database/ But how to load same database for swift 3? As NSPersistentContainer is introduced how can I load .sqlite file which is in my project?


回答1:


Actually the default path where database was created is changed in swift 3 . So now the code will look like :

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

Now you can call this method from AppDelegate's didFinishLaunchWithOptions method and this will preload database which we have put in application.



来源:https://stackoverflow.com/questions/40761140/how-to-pre-load-database-in-core-data-using-swift-3-xcode-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!