0

Integrated SQLITE Database, below is my code which I have written,

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
        self.copyDatabaseIfNeeded()
        return true
}

func copyDatabaseIfNeeded() {
    let fileManager = FileManager.default
    let dbPath = getDBPath()
    var success: Bool = fileManager.fileExists(atPath: dbPath!)
    if !success {
        let defaultDBPath = URL(fileURLWithPath: Bundle.main.resourcePath ?? "").appendingPathComponent(APPLICATION_DB).absoluteString
        success = ((try?fileManager.copyItem(atPath: defaultDBPath, toPath: dbPath!)) != nil)
        if !success {
            print("Failed to create writable database!")
        }
    }
}

func getDBPath() -> String? {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDir = paths[0]
        return URL(fileURLWithPath: documentsDir).appendingPathComponent(APPLICATION_DB).absoluteString
}

It always print below output,

enter image description here

  • Tried clean + Build Project
  • Uninstall the application, reinstall it
  • Remove derived data

none of the above has worked.

Also, my sqlite file is there in project target -> Build Phases -> Copy Bundle Resources : below screenshot for reference.

enter image description here

I am not sure whether hierarchy of my file matters or not, attaching screenshot of that as well.

enter image description here

Can anyone help me why I am getting issue in fetching file path of my database file?

iGatiTech
  • 2,142
  • 1
  • 17
  • 42
  • 1
    did you add breakpoints to see the exception or the issue? – Shabir jan Apr 19 '18 at 05:46
  • Yes I added breakpoints, first condition which is there is for checking file already exists or not so in that I am receiving false. Then again it is fetching path of my local database file from bundle, but again my boolean returns false. I don't know why. File is already there, then it should be true. @Shabirjan – iGatiTech Apr 19 '18 at 05:48
  • 1
    The actual problem is that `absoluteString` does not what you think it does, compare e.g. https://stackoverflow.com/a/39310283 or https://stackoverflow.com/a/34135437. – Martin R Apr 19 '18 at 06:56
  • @MartinR Perfect! Here you catch my mistake. This is want I was mashed up with. Actually I worked with SQLITE in objective-c and in that I had not face this kind of issue. – iGatiTech Apr 19 '18 at 07:52

1 Answers1

1

Try this.

func copyDatabaseIfNeeded() {
    // Move database file from bundle to documents folder

    let fileManager = FileManager.default

    let documentsUrl = fileManager.urls(for: .documentDirectory,
                                                in: .userDomainMask)

    guard documentsUrl.count != 0 else {
        return // Could not find documents URL
    }

    let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("SQL.sqlite")

    if !( (try? finalDatabaseURL.checkResourceIsReachable()) ?? false) {
        print("DB does not exist in documents folder")

        let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("SQL.sqlite")

        do {
              try fileManager.copyItem(atPath: (documentsURL?.path)!, toPath: finalDatabaseURL.path)
              } catch let error as NSError {
                print("Couldn't copy file to final location! Error:\(error.description)")
        }

    } else {
        print("Database file found at path: \(finalDatabaseURL.path)")
    }

}
Shabir jan
  • 2,165
  • 1
  • 19
  • 30