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:
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
}
With @Rob's help, I came to following solution which satisfied my requirement. Previously it was necessary to add sqlite file into xcode project, with proper target.
func prepareDatabaseFile() -> String {
    let fileName: String = "foo.sqlite"
    let fileManager:FileManager = FileManager.default
    let directory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
    let documentUrl= directory.appendingPathComponent(fileName)
    let bundleUrl = Bundle.main.resourceURL?.appendingPathComponent(fileName)
    // here check if file already exists on simulator
    if fileManager.fileExists(atPath: (documentUrl.path)) {
        print("document file exists!")
        return documentUrl.path
    else if fileManager.fileExists(atPath: (bundleUrl?.path)!) {
        print("document file does not exist, copy from bundle!")
        fileManager.copyItem(at:bundleUrl, to:documentUrl)
    }
    return documentUrl.path
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With