启动swift

时间:2017-09-08 20:13:49

标签: ios swift sqlite fmdb

这是我的第一个数据库项目,所以我遇到了一些问题。希望你能帮助我! 我正在使用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)")
    }
}

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

()

我使用错误的方法或实施错误吗?

1 个答案:

答案 0 :(得分:2)

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

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

  1. 获取foo.db路径的代码远非理想。
  2. 您没有妥善处理选项。
  3. 您的变量名称需要改进。示例 - 第二个documentsURL表示它是URL引用"文档"夹。它实际上是资源包中文件的URL
  4. 无需NSError
  5. 以下是我编写此代码的方法:

    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)")
        }
    }