Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 803
Pooja Shah Avatar asked Dec 19 '22 11:12

Pooja Shah


1 Answers

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.

like image 91
Pooja Shah Avatar answered Jan 03 '23 07:01

Pooja Shah