如何使用swift 3 xcode 8在核心数据中预加载数据库 [英] How to pre load database in core data using swift 3 xcode 8
问题描述
我有一个包含数据的数据库,我想在应用程序中预加载它。在swift 3之前它可以工作,我已经按照本教程: http:// www .appcoda.com / core-data-preload-sqlite-database / 但如何为swift 3加载相同的数据库?由于引入了 NSPersistentContainer
,如何加载项目中的.sqlite文件?
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?
推荐答案
实际上,在swift 3中更改了创建数据库的默认路径。所以现在代码看起来像:
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("=======================")
}
}
现在你可以从AppDelegate的 didFinishLaunchWithOptions
方法调用这个方法,这将预装数据库我们已经申请了。
Now you can call this method from AppDelegate's didFinishLaunchWithOptions
method and this will preload database which we have put in application.
这篇关于如何使用swift 3 xcode 8在核心数据中预加载数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!