A lightweight HTTP request class for iOS [1/2]
Part 1 | Part 2
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.
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 implements the
for its callbacks, just like
UIControl. That means
you can write callback methods with sensible names like
trendsComplete, instead of handling everything in a
webRequest:didComplete: method with a ton of
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