从 sqlite 文件加载数据 Swift 4.2

Load data from sqlite file Swift 4.2

我在 sqlite 文件中有大型数据库 所以我试图直接从我的 data.sqlite 文件访问它 但我无法访问它。我过去使用 objective C

完成了该任务

采取的步骤:

1:将data.sqlite文件拖入项目

2:尝试通过 fmdb 访问它

输出:路径=== /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
    }

我没有使用过fmdb,但我在最近的项目中成功使用了GRDB (https://github.com/groue/GRDB.swift)。通常,这些库将允许您在出现错误时检索错误代码或日志输出,这可能对解决您的问题非常有用。

与此同时,这是我用来将文件名转换为完整文档用户路径的 Swift 函数:

    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
    }

但是请注意,作为构建的一部分包含的文件通常不会出现在您的文档中,而是捆绑资源的一部分。在这种情况下,这段代码可能更有用:

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

如果本地数据库文件不存在,请尝试将其复制到应用程序的文档库中。

import FMDB

class DBService {
    // MARK: Properties
    static let shared = DBService()
    var database: FMDatabase!

    private let fileManager = FileManager.default
    private var documentsDBPath: String
    private var resourcesDBPath: String

    private let databaseFileName = "data"
    private let databaseFileName = "sqlite"

    // MARK: Initializers
    private init() {
        documentsDBPath = try! fileManager
            .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            .appendingPathComponent(databaseFileName)
            .appendingPathExtension(databaseFileExtension)
            .path

        resourcesDBPath = Bundle.main.path(forResource: databaseFileName,
                                           ofType: databaseFileExtension)!
    }

    // MARK: - Setup
    func isDatabaseOpen() -> Bool {
        if database == nil {
            initDatabase()
        }

        return database.open()
    }

    private func initDatabase() {
        if isFirstLaunch() {
            copyDatabase(from: resourcesDBPath, to: documentsDBPath)  
        }

        database = FMDatabase(path: documentsDBPath)
    }

    private func isFirstLaunch() -> Bool {
        return !fileManager.fileExists(atPath: documentsDBPath)
    }

    private func copyDatabase(from source: String, to destination: String) {
        do {
            try fileManager.copyItem(atPath: source, toPath: destination)
        } catch {
            debugPrint(error)
        }
    }
}

您的文件显然不在文档目录中,您应该在主包中访问它

let dbUrl = Bundle.main.url(forResource: "data", withExtension: "sqlite")

如果需要复制文档目录下的数据库,请改用下面的方法

let fileManager = FileManager.default
let dbUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("data.sqlite")
if !fileManager.fileExists(atPath: dbUrl.path) {
    let url = Bundle.main.url(forResource: "data", withExtension: "sqlite")!
    try? fileManager.copyItem(at: url, to: dbUrl)
}

用法

let database = FMDatabase(url: dbUrl)