Three ways to make iOS networking less painful with AFNetworking

Posted by | June 26, 2013 | Development | No Comments

When it comes to developing iOS software, iOS networking is something that is a part of almost every project. Whether it be through utilising data from a web service, uploading data, or just downloading a file. We need the process to be asynchronous – that is, the retrieval or uploading of data to a server needs to occur off the main thread. The easy to reach [NSData dataWithContentsOfURL:] method may be the first port of call for retrieving data from the contents of a URL. After all, it’s a simple as supplying a URL and then getting a bunch of data back. This method is synchronous by default, which means the UI will lock up as this method is executed. If the data is large, or the connection speed is poor, this method may take a while to excute, and for this duration the UI will be unresponsive.

NSURLConnection can be used either synchronously or asynchronously, but to the novice iOS programmer, can seem a little complicated and confusing. Luckily, there is an alternative that makes networking much easier called AFNetworking. This library can serve both small and large projects equally as well, and is suitable to both beginners and advanced iOS developers alike. AFNetworking results in fewer lines of code to accomplish the same task. And as any developer will tell you, the less lines of code written, the less oportunity for bugs to arrise.

1. Fetching JSON  Data from a web service using AFNetworking

Interfacing with a RESTful API that returns its data in JSON is a common encounter when making apps that interface with third party services. Here is an example of how easy it is to make a request and turn the JSON into an NSDictionary.


2. Uploading data to a web server

AFNetworking makes it simple to upload data to a webserver and report back the progress of the upload which is useful when the upload is something large, such as an image or a video.


3. Loading UIImageViews with an image from a URL

AFNetworking provides a simple way to populate a UIImageView with an image from a URL. Instead of going through the process of downloading the image (asynchronously), and then having to set the imageView’s image property, AFNetworking provides a category on UIImageView that facilitates the setting of the image property, as well as providing a placeholder image that is displayed while the actual image is in the process of being downloaded.


AFNetworking is a brilliant library to use for all iOS networking needs – if you’ve not used it, you certainly are missing out! You can read the documentation for AFNetworking here, and is available to download on GitHub or using CocoaPods, the excellent Objective-C library manager.

Mobile and Web developer at Yodelay.

    Find out more & get connected:
  • twitter

About Dan Williams

Mobile and Web developer at Yodelay.