Asynchronous [NS]URLConnection With Blocks!

UPDATE: NSURLConnection let’s you do this now on iOS 5+.

Recently I was working on a project and I needed to make a simple API call to a server and monitor the upload/download progress. Importing an entire networking framework like AFNetworking or ASIHTTPRequest seems like an overkill for such a simple task. Using NSURLConnection’s synchronous method (with GCD) won’t magically make it asynchronous, it will still block the entire thread. There’s an overhead because NSURLConnection is asynchronous in nature. Also, there’s no way to get the upload/download progress and you have to wrap it around ugly cryptic GCD methods.  The only option left remaining is implementing the NSURLConnectDelegate protocol but that just makes your class and code look ugly.

So, I wrote this simple class: URLConnection. It’s not just a wrapper around NSURLConnection’s synchronous method using GCD (I’ve seen a lot of people doing that). What you get:

  • Speed that you get out of pure asynchronous implementation of NSURLConnection.
  • Upload progress
  • Download progress
  • Blocks, making everything simple and look clean!
  • No need to import dozens of libraries and frameworks.

Something to keep in mind: The download progress depend on wether the server passes in “Content-Length” parameter in HTTP header field. If that’s not there, there’s no way to determine the progress. In that case, the download completion block will simply not be called.

Here’s a quick example showcasing URLConnection (getting top rated YouTube videos today):

NSURL *url = [NSURL URLWithString:@"https://gdata.youtube.com/feeds/api/standardfeeds/top_rated?time=today"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

[URLConnection asyncConnectionWithRequest:request
 completionBlock:^(NSData *data, NSURLResponse *response) {
 [progress dismiss];
 } errorBlock:^(NSError *error) {
 [progress dismissWithError:@"Error!"];
 } uploadPorgressBlock:^(float progress) {
 //Upload progress (0..1)
 } downloadProgressBlock:^(float progress) {
 //Download progress (0.1)
 }];

Let me know if you find a bug or added something useful to this class and I will update it here.

This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

4 Responses to Asynchronous [NS]URLConnection With Blocks!

  1. aelveon says:

    Great work, thanks a lot!
    I didn’t find any problems.

  2. aelveon says:

    Is there a way to cancel the request?

  3. mazizahmed says:

    Hi aelveon,
    Glad you found a use out of it. No, it’s not possible to cancel it, but it should be easy to implement. Let me know if you need any details on this.

  4. Thanks a lot for this example code. It didn’t quite fit my needs but it was a WONDERFUL head start. It also wasn’t hard to make it work with ARC.

Leave a comment