We are designing Bolina to make all HTTP Libs faster and easily integrate with each one of them so, at some point, I had the task of exploring the iOS HTTP libraries landscape. After having an overview of the most popular ones, I went on to experience how to use them. In the meantime, I put it all on paper to give a hand to anyone looking to have a feeling of what that means.
This hands-on AFNetworking tutorial will show how we can create HTTP requests to download and upload data from a web public API (httpbin.org) using the AFNetworking 3.0 library.
AFNetworking is a well-established library within the iOS developer community and has been growing ever since it’s the first release in 2011. It has a pretty solid and straightforward API and it is an open-source project, which means you can fork it, play around with it and even contribute to its development. In addition, besides supporting all NSURLSession features, AFNetworking provides serialization, reachability support, security policy management, and UIKit integration.
If you used Cocoapods before to manage dependencies, you probably have installed it before. If that’s the case, skip to the next part of the tutorial. If you haven't used it and want to give it a try, you need to install it. To do so, open a terminal and type:
$ sudo gem install cocoapods
This tutorial was developed in Objective-C, although AFNetworking can also be used in a Swift-based project. That said, everything starts with creating the basic skeleton of an Objective-C project’s. After that, there are at least three different ways to install AFNetworking in your early created project, using Cocoapods, Carthage or manual install. Since we will be using Cocoapods, we must close XCode in order to proceed (you can understand why at Cocoapods troubleshooting).
In your terminal, move to your projects directory:
$ cd path/to/your_project
and initiate the Pod dependencies management:
$ pod init
This will create a file named Podfile, in which we will describe the dependencies we need to add to our application target. Next, open the Podfile with you favorite text editor and change it’s content to:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
target 'TargetName' do
pod 'AFNetworking', '~> 3.0'
end
Now, we only need to install the dependencies running:
$ pod install && open <your_project_name>.xcworkspace
AFNetworking should be ready to use, now.
With AFNetworking properly installed, we can now use it, declaring the import at the top of the file (for instance in ViewController.m):
#import “AFNetworking.h”
To perform a simple download add the following method implementation:
If you skip the download example don’t forget to import the AFNetworking header file:
#import “AFNetworking.h”
Similarly to the download example described above, the upload request can be made like this:
You can check out the source project on Github.