2016-11-23 47 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