Mar 2011

A lightweight HTTP request class for iOS [1/2]

Part 1 | Part 2

Check out SMWebRequest on Github.

Let’s say you’re writing an app, either on iOS or the desktop, and you want to download some JSON data from a web service.

With JavaScript and jQuery, this is a one-liner:

Sigh, if only.

Well, technically you could do this in one line:

But if you do that, you’ll block the main thread until it completes, after which I will come over to your house and stab you in the face.

To perform asynchronous, cancellable HTTP requests in Cocoa, we have NSURLConnection. Now, this is a pretty nice class. It gives you a great degree of control over the lifetime of the request and for managing the incoming response data. It also handles caching and system proxy settings and global request pooling and other useful things. So we want to use it.

Unfortunately, using it properly is a bit tedious:

So that’s all fine if we’re only downloading like, one thing in our app. And, maybe for Apple, downloading something from the Internet is a Big Deal.

But if you’re anything like us, your app is pretty much constantly talking to servers. Authenticating, downloading, syncing, sharing, logging, refreshing…there’s easily dozens of places in each of our apps where we need to speak to some web server.

So after a while, we thought “maybe this can suck less!” and wrote a utility class called SMLoadedResource that used NSURLConnection behind the scenes to easily download and process data. Then we threw it away and Benjamin van der Veen wrote it for real and called it SMWebRequest.

SMWebRequest implements the target/action mechanism for its callbacks, just like UIControl. That means you can write callback methods with sensible names like trendsComplete, instead of handling everything in a generic webRequest:didComplete: method with a ton of if statements.

SMWebRequest also provides incredibly nice support for parsing your response data in a background thread while maintaining a separation of concerns. For more, continue to Part 2.

Notes (From Tumblr)

  1. hlung reblogged this from nfarina
  2. copywriter-copywriting reblogged this from nfarina
  3. jjoaquim reblogged this from nfarina
  4. nfarina posted this