harlan kellaway's blog // iOS How-To - Pre-loading Core Data on App Launch

Published 02-20-2015

I am in the process of finishing up an app and just wrestled with the process of retrieving an sqlite db to include in the app to pre-populate Core Data on first download. There are many processes of how to get this done; I thought I'd share mine.

Step 1: Generate the sqlite DB

My app fetches JSON using AFNetworking and translates the result into objects that are then saved to Core Data. Typically, my application only fetched up to 100 objects at a time - but my seed DB will have ~5700 objects. Given I had already built the functionality to read in JSON, translate, and save to Core Data, I chose to generate my sqlite DB by doing a special run of my application that pointed to a JSON file where all 5700 objects were listed.

I did a run of my application using the iPhone Simulator, successfully retrieving, translating, and saving.

Step 2: Retrieve the sqlite DB

The sqlite file was output to the following file path:

/Users/[USERNAME]/Library/Developer/CoreSimulator/Devices/[ID]/data/Containers/Data/Application/[ID]/Documents/[DATA MODEL NAME].sqlite

where [ID] is the 32-character alphanumeric identifier of the latest run - this will be different each run.

Step 3: Verify data (optional)

I used the Core Data Editor application to view my data and verify the expected amount of objects were created in my sqlite store. Core Data Editor also expects a .mom file (this tells it the structure of your data). I found this file at the following path:

/Users/[USERNAME]/Library/Developer/CoreSimulator/Devices/[ID]/data/Containers/Bundle/Application/[ID]/[APP NAME].app/[DATA MODEL NAME].momd/[DATA MODEL NAME].mom

Step 4: Load data programmatically

I placed the following code in the `persistentStoreCoordinator` method of my `AppDelegate` AFTER the `storeURL` variable is declared:

if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL path]])
     NSURL *preloadURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:[SQLITE DB NAME] ofType:@"sqlite"]];
    NSError* error = nil;

    if (![[NSFileManager defaultManager] copyItemAtURL:preloadURL toURL:storeURL error:&error])
Happy coding!

This blog is licensed under Attribution-Noncommercial-Share Alike 3.0 Unported license.

comments powered by Disqus