在Xcode项目中哪里找到Sqlite数据库 [英] Where to locate Sqlite database in Xcode project

查看:535
本文介绍了在Xcode项目中哪里找到Sqlite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉重复一个问题,尽管稍有不同,但是我已经尝试了所有方法,在此论坛和Google上进行了搜索,但无法解决此问题。我有一个Sqlite数据库(只有20kb大小),我想在使用Xcode的Swift 4项目中使用它。我已将数据库(.db文件)放在Xcode保存项目的文件夹中,但是当我运行该应用程序时,出现无此表错误。在调试屏幕中遵循文件路径,将我带到0kb的文件,即空文件。我以为我已经通过使用路径名(即FileManager.default.fileExists(atPath: / Users / ...))解决了这个问题,但是它在我的iPhone上不起作用(仅在Simulator中),所以我走了回到尝试使用URL方法。我已经复制了大部分代码,但是我怀疑前几行有问题,或者我没有在正确的位置提交.db文件。将其添加到项目检查器中,并将其与作为目标的项目相关联,并显示在构建阶段屏幕的副本捆绑资源下方。我在这里很挣扎,因此非常感谢任何帮助。

Sorry for repeating a question albeit slightly differently but I've tried everything, searched this forum and google but can't solve this issue. I have a Sqlite database (only 20kb size) which I want to use in a Swift 4 project using Xcode. I've put the database (a .db file) in the folder where Xcode saved my project but when I run the app I get the 'no such table error'. Following the file path in the debug screen takes me to a file of 0kb i.e. empty. I thought I'd solved this by using the path name (i.e. FileManager.default.fileExists(atPath: "/Users/...") but it won't work on my iPhone (only in Simulator) so I've gone back to trying to use the URL approach. I've copied the main bit of code but my suspicion is that there is something either wrong with the first few lines or I haven't filed the .db file in the right place. I have added it to the project inspector, it is associated with the project as the target and it shows under the copy bundle resource bit of the build phases screen. I'm really struggling here so any help really appreciated.

//Function to open Cities database, add cities to array, sort alphabetically and then append "Please select city" at the start of the array
func populatePickerView() {
    let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let databaseURL = fileURL.appendingPathComponent("Wanderer.db")
    let database = FMDatabase(path: databaseURL.absoluteString)

    guard database.open() else {
        print("Unable to open database")
        return
    }

    do {
        let cities:FMResultSet = try database.executeQuery("SELECT City from Cities", values: nil)

        while cities.next() {
            if let result = cities.string(forColumn: "City") {
                cityData.append(result)
            }
        }
    } catch {
        print("OOPS, some sort of failure")
    }

    cityData = cityData.sorted(by: <)
    cityData.insert("Please select city", at: 0)
}


推荐答案

如果拖动并将数据库拖放到Xcode项目结构中,并选择如果需要复制项目,然后选择目标,数据库位于此处:

If you drag and dropped your database to your Xcode project structure with "copy items if needed" and your target selected, your database is located here:

let databaseInMainBundleURL = Bundle.main.resourceURL?.appendingPathComponent("Wanderer.db")

如果您只想读取数据,这很好,因为主要束是只读的。

If you just want to read the data this will be fine, because the main bundle is read only.

如果要在数据库中保存某些内容,则需要将数据库复制到documents目录。

If you want to save something in your database you need to copy the data base to the documents directory.

您可以使用此功能检查文档目录中是否存在数据库,并根据需要进行复制。

You can use this function to check if your database exists in document directory and copy if needed.

func copyDatabaseIfNeeded(_ database: String) {

    let fileManager = FileManager.default

    let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask)

    guard documentsUrl.count != 0 else {
        return
    }

    let finalDatabaseURL = documentsUrl.first!.appendingPathComponent("\(database).db")

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

        let databaseInMainBundleURL = Bundle.main.resourceURL?.appendingPathComponent("\(database).db")

        do {
            try fileManager.copyItem(atPath: (databaseInMainBundleURL?.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)")
    }
}

和配合使用:

copyDatabaseIfNeeded("Wanderer")

之后,您将可以使用 populatePickerView 函数。

After that you will be able to use your populatePickerView function.

这篇关于在Xcode项目中哪里找到Sqlite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆