iOS: Downloading and parsing JSON

Recently I set out to update an iPhone app with the ability to accept updates from our server. The plan is to let the app download a JSON file off our web server and update the internal data accordingly. Pretty simple right? It is pretty simple, but many tutorials focus on some aspects that don’t fit with ever project out there so I hope this contributes some “basic knowledge”.

To keep this simple, I’m only going to concentrate on downloading the data from a server and parsing that data. No Core Data, no SQLite, no table views. I’m not going to tell you how to build a Flickr app or a Twitter app. Just download the data and parse. What I’m using: Xcode 3.2.5, ASIHTTPRequest 1.8, and JSON Framework 2.3.1.

First we need to download our data and we want this to happen in the background so that the user can keep using the app. This is important for mobile apps: you don’t know how long a download is going to take, even if you know that your data is less tiny. So, as far as my research showed, this meant that NSURLRequest is off the table since it apparently creates a synchronous connection (freezing the thread it is running in). I’m guessing you could throw that request into another thread but there are libraries that handle asynchronous requests.

I’ve used ASIHTTPRequest so far after failing to get HTTPRiot to work. Initially I tried to work with HTTPRiot since it parses JSON for you. I struggled for hours getting things configured correctly and started coding up my model and nothing. I spent a good chuck of a day on it and it wasn’t working for me. That’s not the end of the world, but I figured I’d given ASIHTTPRequest a try and I had a request working in less time than it took for me to get HTTPRiot to compile (this is not a fault of HTTPRiot, but perhaps of my own weaknesses when it comes to setting up libraries in Xcode).

So download ASIHTTPRequest and move all the files from the “Classes” folder into your app. Also add the “Reachability” folder from “External” as well. I placed these all in a folder called ASIHTTPRequest and then added existing files in Xcode, but that’s personal preference I suppose. Also follow the setup steps to add some other frameworks. Build to see if everything is working.

Then create a method in the view controller, called updateData (or whatever you like) and add this code:

That code is setting the delegate to self, so our view controller needs to respond to the data:

And that’s it. You’re downloading your data and parsing it! Simple. Now you just need to do stuff with it!