ios - 如何使用 swift 3 xcode 8 在核心数据中预加载数据库

标签 ios swift xcode swift3 xcode8

我有一个包含数据的数据库,我想在应用程序中预加载它。在 swift 3 之前它可以工作,我遵循了本教程:http://www.appcoda.com/core-data-preload-sqlite-database/但是如何为 swift 3 加载相同的数据库?随着 NSPersistentContainer 的引入,我如何加载项目中的 .sqlite 文件?

最佳答案

实际上,创建数据库的默认路径在 swift 3 中发生了变化。所以现在代码看起来像:

func preloadDBData() {
    let sqlitePath = Bundle.main.path(forResource: "MyDB", ofType: "sqlite")
    let sqlitePath_shm = Bundle.main.path(forResource: "MyDB", ofType: "sqlite-shm")
    let sqlitePath_wal = Bundle.main.path(forResource: "MyDB", ofType: "sqlite-wal")

    let URL1 = URL(fileURLWithPath: sqlitePath!)
    let URL2 = URL(fileURLWithPath: sqlitePath_shm!)
    let URL3 = URL(fileURLWithPath: sqlitePath_wal!)
    let URL4 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite")
    let URL5 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite-shm")
    let URL6 = URL(fileURLWithPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite-wal")

    if !FileManager.default.fileExists(atPath: NSPersistentContainer.defaultDirectoryURL().relativePath + "/MyDB.sqlite") {
        // Copy 3 files
        do {
            try FileManager.default.copyItem(at: URL1, to: URL4)
            try FileManager.default.copyItem(at: URL2, to: URL5)
            try FileManager.default.copyItem(at: URL3, to: URL6)

            print("=======================")
            print("FILES COPIED")
            print("=======================")

        } catch {
            print("=======================")
            print("ERROR IN COPY OPERATION")
            print("=======================")
        }
    } else {
        print("=======================")
        print("FILES EXIST")
        print("=======================")
    }
}

现在您可以从 AppDelegate 的 didFinishLaunchWithOptions 方法调用此方法,这将预加载我们已放入应用程序的数据库。

关于ios - 如何使用 swift 3 xcode 8 在核心数据中预加载数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40761140/

相关文章:

ios - didReceiveRemoteNotification :fetchCompletionHandler: but the completion handler was never called

Xcode 4 无法启动

arrays - 用字典应用 Array.map

json - vapor `client.get` ,转换返回json

xcode - 将上下文管理器添加到单个 View 应用程序

iphone - Objective-C 委托(delegate)类型

ios - fopen$UNIX2003 在外部库内失败

ios - 如何在 PhoneGap 构建中使用 SVG 图像作为启动画面?

iOS-图表 : Increasing bar width in grouped sets of BarChartView

ios - 使用 RestKit 执行同步请求