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?
-
Did find any solution ?Lokesh Chowdary– Lokesh Chowdary2016-12-30 04:58:06 +00:00Commented Dec 30, 2016 at 4:58
-
@LokeshChowdary yes.check I have added my answer and it works perfectly fine.Pooja Shah– Pooja Shah2016-12-30 06:12:31 +00:00Commented Dec 30, 2016 at 6:12
Add a comment
|
1 Answer
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.
5 Comments
Lokesh Chowdary
Pooja: Have you done above code for iOS 9.0 support ?
user2931321
@pooja Shah Have you done above code for ios 9.0 ? If so please help me.
pkc
@LokeshChowdary , Pooja: Have you worked with csv in the same project(appcoda.com/core-data-preload-sqlite-database)? I need to fetch data from csv and shown in table view.
Pooja Shah
@pkc456 You can directly convert csv file to db using tool name: sqlite or mesa sql then use that DB in app.
iOS_User
@PoojaShah : hey my app is crashed because in my application bundle I don't have all 3 files, Where from I extract 3 files. actually I follow the appcoda.com/core-data-preload-sqlite-database tutorial and print the document path but not found any single file there.. Please help me out, thanks in advance..!