启动swift后复制数据库

Ove*_*ned 2 sqlite fmdb ios swift

这是我的第一个数据库项目,所以我面临一些问题。希望你能帮助我!我正在使用 FMDB 来访问现有数据库。当我尝试执行像“选择 * 从电影”这样的简单查询时,它会返回“没有这样的表”之类的东西。我查看了 iPhone 模拟器的文件夹并找到了数据库,但它是空的。我的下一步是,包括这个方法:

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("foo.db")

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

        let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("foo.db")

        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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

但是这个方法不起作用。我从 DidFinishLaunching 调用它。

这是错误消息:

OverBurned/Library/Developer/CoreSimulator/Devices/B5EAE004-A036-4BD5-A692-C25EF3875D25/data/Containers/Bundle/Application/5ABA8D38-7625-4F98-83E9-4266A3E5B6B0/GameOne.app/foo.db, NSUnderlyingError=0x600000053230 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
Run Code Online (Sandbox Code Playgroud)

()

我是使用错误的方法还是执行错误?

rma*_*ddy 5

错误很明显。有没有foo.db在你的应用程序的资源包。

您发布的代码确实有很多问题。

  1. 您获取路径的代码foo.db远非理想。
  2. 您没有正确处理选项。
  3. 您的变量名称需要改进。示例 - 第二个documentsURL暗示它是URL引用“文档”文件夹。它实际上是URL资源包中的一个文件。
  4. 没有必要NSError

以下是我将如何编写此代码:

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

    let fileManager = FileManager.default

    guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    let finalDatabaseURL = documentsUrl.appendingPathComponent("foo.db")

    do {
        if !fileManager.fileExists(atPath: finalDatabaseURL.path) {
            print("DB does not exist in documents folder")

            if let dbFilePath = Bundle.main.path(forResource: "foo", ofType: "db") {
                try fileManager.copyItem(atPath: dbFilePath, toPath: finalDatabaseURL.path)
            } else {
                print("Uh oh - foo.db is not in the app bundle")
            }
        } else {
            print("Database file found at path: \(finalDatabaseURL.path)")
        }
    } catch {
        print("Unable to copy foo.db: \(error)")
    }
}
Run Code Online (Sandbox Code Playgroud)