URL Requests

Your apps will often be required to communicate with a remote server. URL requests are fairly complex and can fail for many reasons: the remote server can’t be reached, the remote server doesn’t understand your request, you don’t understand the server’s response, etc.

Luckily for us, there are many ways to communicate over the network on iOS. We will first look at the relevant Foundation framework classes , then explore a third-party tool that automates much of the process without taking away too much control.

Using the Foundation framework

Many classes are required to build a simple request:

  • NSURL references a URL address.
  • NSURLRequest represents this URL and holds a content cache policy.
  • NSURLConnection actually performs the connection and receives a response.
  • NSData is the container used to store the response data, before it can be interpreted.

As it takes time to perform a request and receive a response, this operation is often done asynchronously, on a separate thread. This allows our app to continue running while the operation is happening. If we were performing the request synchronously, the entire app would hang until a response was received.

As you may have already guessed, asynchronous requests are performed using delegation. The NSURLConnectionDelegate can implement many methods to receive constant status updates on the state of the request.

You can also check for connection errors before proceeding, by making sure that NSURLConnection is valid.

You can also check for errors during the operation, by implementing connection:didFailWithError:.

This example works properly because our response is small. Larger responses will come in chunks, and will call connection:didReceiveData: multiple times. For every call, you would need to append the new data to the old one until the operation is complete.


This is already a lot of overhead for what appears to be a trivial request, but all these steps are necessary as there is a lot is going on behind the scenes. There have been many attempts to simplify this process for programmers, and there are many solid tools out there that you can use. One of these tools is AFNetworking.

AFNetworking is a good solution because:

  • It inherits from Foundation classes and allows you to “step in” and use the NSxxx methods and objects if you need to.
  • It provides default settings and convenient setters and getters for headers, authentication, network reachability, batched operations, etc.
  • It distinguishes errors from successful requests using status codes and response types.
  • It includes media-specific request operations that transform NSData into more useable formats, like JSON, XML, and even images.
  • It uses blocks instead of delegation to handle callbacks, keeping together all the relevant code to an operation.

  1. URL Loading System Programming Guide. Apple, Jan 9 2010.
  2. AFNetworking. Mattt Thompson, Visited Oct 2 2012.

Comments are closed.