2016-11-23 46 views
2

我有一個數據庫和數據,我想在應用程序中預加載。在swift 3之前,它的工作原理和我遵循本教程:http://www.appcoda.com/core-data-preload-sqlite-database/但是如何爲swift 3加載相同的數據庫? As NSPersistentContainer is introduced如何加載我的項目中的.sqlite文件?如何使用swift 3預加載數據庫核心數據xcode 8

+0

找不到解決方案? –

+0

@LokeshChowdary yes.check我已經添加了我的答案,它工作得很好。 –

回答

7

實際上創建數據庫的默認路徑在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方法這個方法,這將預裝我們已經把應用程序數據庫。

+0

Pooja: - 它的工作...你救了我的一天.. tnx .. –

+0

Pooja:你有沒有完成上面的代碼爲iOS 9.0的支持? –

+0

@pooja Shah你已經完成了ios 9.0的代碼嗎?如果有,請幫助我。 – user2931321