Persist JSON to a Realm model layer

January 10, 2019

(Full source code for this post: https://github.com/joshbuddha/Walk-Talk.git)

I have a music player in a current Swift project that is defined by data baked in a .plist file. In this post i’ll walk you through how I made the song data for the application editable on the server.

1. Define the JSON data and save the db.json in your project folder. I’m using json-server to simulate the rest api call. For more info on setting up json-server checkout https://github.com/typicode/json-server.

2. Install Realm. It is already setup in the source files. If you want to set it up on your own add “pod ‘RealmSwift'” to your Podfile and run Pod install.

3. Create the DBLayer struct. The DBLayer will load the JSON with URLSession, decode the the JSON, and add each Track object to the Realm data store.

4. Create the Track class so that the JSON can be decoded. They dynamic vars are setup to work with Realm and the Coding Keys are also setup in case we ever needed to redefine the property names.

5. Setup the ViewController to display the list of songs from the server. The main class variables the the DBLayer to make the network call, The Realm Results to retrieve the Track data, and a token for responding the database changes.

6. Within viewDidLoad is where you will setup the DBLayer, load the JSON, setup Realm to observe database changes, and initialize the myTracks array for the tableview display.

This approach makes it easy to update the content of the music player. Also the UI will update anytime the database layer is changed. You can test this by changing the db.json file and hitting the update button to simulate a service call.

Here is the entire ViewController class:

Once again all the code is here:
https://github.com/joshbuddha/Walk-Talk.git

Thanks for following along,
Josh