iosswiftsqlitefmdb

Load data from sqlite file Swift 4.2


enter image description hereI have large database in sqlite file so I am trying to access it directly from my data.sqlite file but I am not able to access it . I had achieved that task in past using objective C

Steps Taken:

1:Drag data.sqlite file into project

2:Trying to access it via fmdb

Output: path=== /var/mobile/Containers/Data/Application/557B2961-52D8-4B14-BABC-BF4829852127/Documents/data.sqlite

let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String 
pathToDatabase = documentsDirectory.appending("/(databaseFileName)")

func openDatabase() -> Bool {
 print("path=== \(pathToDatabase ?? "empty")")
      if database == nil {
           if FileManager.default.fileExists(atPath: pathToDatabase) {
                database = FMDatabase(path: pathToDatabase) 
//code is not entering in that if , it should be there becasuse I already included my sqlitefile    
 } 
        if database != nil {
            if database.open() {
                return true
            }
        }
        return false
    }

Solution

  • I have not used fmdb but I have used GRDB (https://github.com/groue/GRDB.swift) successfully in a recent project. Usually, those libraries will allow you to retrieve an error code or log output whenever there is an error and this may prove really useful in solving your issue.

    In the meantime, here's a Swift function I'm using to convert a filename into a full Documents user path:

        private static func path(for filename: String) -> String {
            let fm = FileManager.default
            let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first
            return documentsDirectory?.appendingPathComponent(filename).absoluteString ?? filename
        }
    

    Note however, that files that are included as part of the build will typically not be in your Documents, it will be part of the bundle resources. In which case this piece of code may be more useful:

        let path = Bundle.main.path(forResource: "mydatabase", ofType: "sqlite")