I'm trying to upload my sqlite database file into an application. I've been learning about the iOS file system, and I'm not completely sure how it works and got lost. This is what I would like to achieve, but not sure how:
- I would like to have database on this location my-xcode-project-path/data/foo.sqlite. Now I'm running simulator for first time, and I would like to copy this database into simulator's Document directory.
- In case if I had the application already installed, I would skip step 1. and copy database from bundle.
- If I tried to run simulator, but don't have file available in bundle, I would like to keep that database.
Thank you in advance!!!
My code is looking like this:
func prepareDatabaseFile() -> String {
let fileName: String = "foo.sqlite"
let filemanager:FileManager = FileManager.default
let directory = filemanager.urls(for: .documentDirectory, in: .userDomainMask).first!
let newUrl = directory.appendingPathComponent(fileName)
let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName)
// check bundle
if filemanager.fileExists(atPath: (bundleUrl?.path)!) {
print("bundle file exists!")
return (bundleUrl?.path)! //probably I need to copy from bundle to new app and return new url
// here check if file already exists on simulator, but not in bundle
} else if filemanager.fileExists(atPath: (newUrl.path)) {
print("prebuild file exists!")
return newUrl.path //no copy is needed
// finally, if nothing I need to copy local file
} else {
//todo copy local file from the path my-xcode-project-path/data/foo.sqlite
print("todo")
}
return fileName
}
sqlite3_open_v2with "readwrite" option, but not "create" option), and only if it failed (or the version was old) would I copy from bundle and then open it again. It is more efficient, because generally when the user fires up the app, the db is there already; it's only the first time (or every upgrade) that you might need to copy. To get more specific, we'd need to know how you're interacting with SQLite. I.e. some library or are you doingsqlite3_xxxcalls yourself?