Any Way to Pre Populate Core Data

Any way to pre populate core data?

Here's the best way (and doesn't require SQL knowledge):

Create a quick Core Data iPhone app (Or even Mac app) using the same object model as your List app. Write a few lines of code to save the default managed objects you want to the store. Then, run that app in the simulator. Now, go to ~/Library/Application Support/iPhone Simulator/User/Applications. Find your application among the GUIDs, then just copy the sqlite store out into your List app's project folder.

Then, load that store like they do in the CoreDataBooks example.

Deploy app with pre-populated Core Data

This is the solution I found:

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

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

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

Copy this in 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
}()

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

swift ios does core data have any function to pre populate

Do you really need Core Data? If all you need is access to your relational data, I'd create a SQLite database from your SQL dumps on your PC. Then you can include that file in your app's bundle during the "Copy Resources" step. SQLite is available on iOS, so you'd be good to go.

Pre Populate Core Data with a method

Solution:

Warning, you have to delete the module in the Data Model Inspector and set it to global namespace.

Sample Image

You have to do this on your code:

    let fetchRequest : NSFetchRequest<NSFetchRequestResult>

if #available(iOS 10.0, *) {
fetchRequest = Params.fetchRequest()
} else {
fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Params")
}

//let predicate = NSPredicate(format: "key=%@", key)
//fetchRequest.predicate = predicate

do {
let results = try context.fetch(fetchRequest)

if(results.count != 0){

let params = NSEntityDescription.insertNewObject(forEntityName: "Params", into: context) as! Params

params.setValue(value, forKey: "value")

do {
try context.save()
} catch let error as NSError {
print ("Error first demande insertion \(error)")
}

} else if (results.count == 0) {

let params = NSEntityDescription.insertNewObject(forEntityName: "Params", into: context) as! Params

params.key = key
params.value = value

context.insert(params)
}


} catch {
let fetchError = error as NSError
print(fetchError)
}

How to import pre-populated Core Data and load it within the app

Well not sure if this is what you're looking for. But this could work too, at least it did for me.

Well as the story goes there was a client that wanted the app to start with a given set of data. Usage of CoreData was not a requirement though, but I wanted to learn it out of desperation(as it had already cost me a couple of jobs).

So here's what I did. I loaded up the SQLite with the data that client wanted and on first launch of the app I simply accessed those values from SQLite DB and updated my CoreData with it. From then onward I just referred to the CoreData.

A hack or even an unnecessary added step, i know, but it did get the job done.

Though at the end of it I would just say use an SQLite DB if you want pre-populated data.

Hope it helps. Feel free to ask if you have further questions.

How to add many objects into core data?

Proceed in two stages.

  1. In stage one, create the core data database and store the 5000 objects in it. Now remove that code (or arrange so that you never run it again), and copy that database into your app bundle.

  2. So in stage two, your app launches, copies the database out to the documents folder (if it isn't there already), accesses it, and uses it.

Thus, when the end user actually comes to use your app, there's the database all prepared and ready to use instantly, because the user experiences only stage two.



Related Topics



Leave a reply



Submit