Programming: Working With JSON

Today, I explored the possibility of retrieving the data from a server. This was experimented briefly before, but as the final idea developed, it seemed less relevant.

However, I had the idea that rather than filling the app’s code with all of the text for the details page, it could be fetched from a server instead. To do this I used a Swift extension called SwiftyJSON. This significantly simplifies the process of fetching data from the server, making the code work better and much easier to read, write and understand.

To start with, I created an array of strings to store all the detail text fetched from the server. The array is made outside of the function used to fetch the data so that it can be used globally, rather than only inside the function. The function, loadDetailText(), is what we call to do the JSON request. The function gets the .json file from a server (in this case my web server as a test) and then reads the data it collects. I used a loop to iterate through the JSON array, and used each iteration to fill a space in the local detailArray.

Screen Shot 2015-05-03 at 18.15.17

Below is an image of how the JSON file looks. It is set up as an array of detailText with each detailText havingĀ a string. These strings populate the detailArray allowing us to access them individually when needed to place the text in the app.
Screen Shot 2015-05-03 at 18.15.42

At the moment, we are unsure which approach would be best for the application, either embedding the text into the app, or fetching it from a server. Embedding into the code currently seems to be the best idea, as it means an internet connection isn’t required to use the application. However this experiment with JSON is still valuable as a fallback if ever needed.