How to deliver app with prefilled realm-database

swalkner picture swalkner · Apr 24, 2015 · Viewed 9.2k times · Source

I would like to deliver my app with already prefilled data in my realm database. Do I have to simply copy it to the documents directory or is there some other things to do?

Answer

jpsim picture jpsim · Apr 24, 2015

Realm's documentation has a section on "Bundling a Realm with an App":

It’s common to seed an app with initial data, making it available to your users immediately on first launch. Here’s how to do this:

  1. First, populate the realm. You should use the same data model as your final, shipping app to create a realm and populate it with the data you wish to bundle with your app. Since realm files are cross-platform, you can use an OS X app (see our JSONImport example) or your iOS app running in the simulator.

  2. In the code where you’re generating this realm file, you should finish by making a compacted copy of the file (see -[RLMRealm writeCopyToPath:error:]). This will reduce the Realm’s file size, making your final app lighter to download for your users.

  3. Drag the new compacted copy of your realm file to your final app’s Xcode Project Navigator.

  4. Go to your app target’s build phases tab in Xcode and add the realm file to the “Copy Bundle Resources” build phase.

  5. At this point, your bundled realm file will be accessible to your app. You can find its path by using [[NSBundle mainBundle] pathForResource:ofType:].

  6. You can either create a read-only realm by calling [RLMRealm realmWithPath:readOnly:error:]. Or, if you’d like to create a writable realm file based on this initial data, you can copy the bundled file to your application’s Documents directory using [[NSFileManager defaultManager] copyItemAtPath:toPath:error:] and then construct your new realm by using [RLMRealm realmWithPath:].

You can refer to our migration sample app for an example of how to use a bundled realm file.