dyatesupnorth dyatesupnorth - 1 year ago 127
Swift Question

Swift Importing Large JSON data Set and Core Data

What would be the best approach to performing a large JSON data request and storing it in Core Data?

I am currently getting a JSON file from the server which contains a list of jobs with associated entities, I am then parsing it and populating a Core Data Entity, which works fine.

When the user refreshes their list I will be performing a fresh request to the server so I assume I will need to completely remove all existing entities and repopulate the DB.

How is this kind of operation best achieved in Swift?

I have found a couple of tutorials and examples using Dataseeding which seems close enough.

If you need some examples or existing code please let me know

Answer Source

This question has been asked and answered many many times on Stack Overflow. You are wanting to import data and then on a refresh you want to solve the classic insert/update problem.

You want to be doing this import on a background thread to avoid interrupting your UI.

You do not want to delete all objects. You want to use KVC to get all the IDs from the incoming JSON then do a single fetch against CD to find out what already exists.

You then want to iterate over the JSON, inserting if it doesn't already exist and updating when it does exist.

Since your UI should be using a NSFetchedResultsController, you will then just need to save your private NSManagedObjectContext and your UI will update as a result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download