使用预先填充的核心数据部署应用 [英] Deploy app with pre-populated Core Data

查看:96
本文介绍了使用预先填充的核心数据部署应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用已填充核心数据的应用程序进行运输。我找到了一些链接,他们在其中解释了操作方法,但要么行不通,要么答案很旧。我关注了帖子但这不起作用。一种解决方案是将 .sqlite 文件导入到应用文件夹,然后将其复制到设备的文件系统中,但是我不知道该怎么做。有什么方法可以用现有实体和记录来预填充我的核心数据吗?

I'm trying to ship my app with Core Data already populated. I found some links where they explain how to do it, but either it doesn't work or the answers are very old. I followed this post but it doesn't work. A solution could be to import .sqlite files to the app folder and then copy them to device's file system, but I can't figure out how to do it. Are there any ways to pre-populate my Core Data with existing entities and records?

推荐答案

这是我发现的解决方案:

This is the solution I found:

第1步

在另一个应用程序中填充您的核心数据并使用以下代码获取文件的路径:

Step 1
Populate your Core Data in another app and get files' path using this code:

let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
print(documentsDirectory)

Step2

将扩展名为 .sqlite 的3个文件拖到xCode项目中。 (请确保选择添加到目标选项)。

Step2
Drag your 3 files with .sqlite extension into your xCode project. (Be sure to select Add to targets option).

Step3

创建函数以检查应用程序的首次运行。

Step3
Create function to check app's first run.

func isFirstLaunch() -> Bool {
    let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
    let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
    if (isFirstLaunch) {
        UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
        UserDefaults.standard.synchronize()
    }
    return isFirstLaunch
}

Step4

将其复制到 AppDelegate

func getDocumentsDirectory()-> URL {
    let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

// MARK: - Core Data stack

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "ProjectName")

    let appName: String = "ProjectName"
    var persistentStoreDescriptions: NSPersistentStoreDescription

    let storeUrl = self.getDocumentsDirectory().appendingPathComponent("FileName.sqlite")

    if UserDefaults.isFirstLaunch() {
        let seededDataUrl = Bundle.main.url(forResource: "FileName", withExtension: "sqlite")
        try! FileManager.default.copyItem(at: seededDataUrl!, to: storeUrl)
    }

    let description = NSPersistentStoreDescription()
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.url = storeUrl

    container.persistentStoreDescriptions = [description]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

步骤5

如果要删除新的 Core Data 文件,请使用以下功能:

Step 5
If you want to delete your new Core Data files, use this function:

func deleteFiles() {
    let fileManager = FileManager.default
    let documentsUrl =  FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! as NSURL
    let documentsPath = documentsUrl.path

    do {
        if let documentPath = documentsPath {
            let fileNames = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
            print("all files in cache: \(fileNames)")
            for fileName in fileNames {
                if (fileName.contains("YourFileName")) {
                    let filePathName = "\(documentPath)/\(fileName)"
                    try fileManager.removeItem(atPath: filePathName)
                }
            }
            let files = try fileManager.contentsOfDirectory(atPath: "\(documentPath)")
            print("all files in cache after deleting images: \(files)")
        }
    } catch {
        print("Could not clear temp folder: \(error)")
    }
}

这篇关于使用预先填充的核心数据部署应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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