将数据库文件从包移动到文档文件夹 - FMDB [英] Move database file from bundle to documents folder - FMDB

查看:26
本文介绍了将数据库文件从包移动到文档文件夹 - FMDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 FMdatabase.我想使用准备好的数据库.

I'm using FMdatabase. I want to use a prepared database.

我想我应该将数据库文件从包移动到文档文件夹.

I think I should move database file from bundle to documents folder.

我的代码:

import FMDB
class DatabaseManager {

    private let dbFileName = "kashanmapDB_upgrade_3-4.db"
    private var database:FMDatabase!

    let TABLE_LOCATION_FA           = "LocationInfoFa";
    let TABLE_LOCATION_EN           = "LocationInfoEn";
    let TABLE_GREAT_PEOPLE_FA       = "GreatPeopleInfoFa";
    let TABLE_GREAT_PEOPLE_EN       = "GreatPeopleInfoEn";
    let TABLE_TAGS                  = "Tags";
    let TABLE_RELATION_TAG_LOCATION = "RelationTagLocation";
    let TABLE_NECESSARY_INFORMATION = "NecessaryInformation";
    let TABLE_SLIDER_FA             = "SliderFa";
    let TABLE_SLIDER_EN             = "SliderEn";
    let DATABASE_VERSION            = 4;
    static var LANGUAGE                    = 1 ; //1:Fa , 2:En
    var utilities                   = Utilities()

    init() {
        openDatabase()

        if(utilities.getData(key: "lang") == "2")
        {
            DatabaseManager.LANGUAGE = 2
        }

    }

    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("kashanmapDB_upgrade_3-4.db")
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let finalDatabaseURL = URL(fileURLWithPath: paths).appendingPathComponent(dbFileName)

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

            let documentsURL = Bundle.main.resourceURL?.appendingPathComponent("kashanmapDB_upgrade_3-4.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)")
        }

    }

    func openDatabase() {

        self.copyDatabaseIfNeeded()

        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
        let dbPath = URL(fileURLWithPath: paths).appendingPathComponent(dbFileName)

        let str_path = Bundle.main.resourceURL!.appendingPathComponent(dbFileName).path
        let database = FMDatabase(path: str_path)

        /* Open database read-only. */
        if (!(database.open(withFlags: 2))) {
            print("Could not open database at \(dbPath).")
        } else {
            print("opened database")
            self.database = database;
        }
    }

第一次(安装应用程序时)我收到此错误消息:

at the first time (when application installed ) I got this error message:

DB does not exist in documents folder

我总是收到这条消息:

Error Domain=FMDatabase Code=8 "attempt to write a readonly database" UserInfo={NSLocalizedDescription=attempt to write a readonly database}

推荐答案

嗯...看你的代码:

func openDatabase() {

    self.copyDatabaseIfNeeded()

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
    let dbPath = URL(fileURLWithPath: paths).appendingPathComponent(dbFileName)

    let str_path = Bundle.main.resourceURL!.appendingPathComponent(dbFileName).path
    let database = FMDatabase(path: str_path)

    /* Open database read-only. */
    if (!(database.open(withFlags: 2))) {
        print("Could not open database at \(dbPath).")
    } else {
        print("opened database")
        self.database = database;
    }
}

看来您正在将 dbPath 设置为等于文档文件夹中文件的路径,但随后您试图打开位于 str_path 的 database 等于 Bundle 路径.

It appears you are setting dbPath equal to the path to the file in documents folder, but then you're trying to open database which is at str_path which is equal to the Bundle path.

也许只是改变:

let database = FMDatabase(path: str_path)

到:

let database = FMDatabase(path: dbPath)

这篇关于将数据库文件从包移动到文档文件夹 - FMDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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