启动后复制数据库 swift

Copy Database after starting swift

这是我的第一个数据库项目,所以我遇到了一些问题。希望你能帮助我! 我正在使用 FMDB 访问现有数据库。当我尝试执行像 "Select * From films" 这样的简单查询时,它 returns 像 "no such table" 这样的东西。我查看了 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)")
    }
}

但是这个方法不起作用。我从 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"}}

()

我是使用了错误的方法还是实施错误?

错误很明显。您应用的资源包中没有 foo.db

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

  1. 您获取 foo.db 路径的代码远非理想。
  2. 你没有正确处理可选值。
  3. 您的变量名需要改进。示例 - 第二个 documentsURL 表示它是引用 "Documents" 文件夹的 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)")
    }
}