Page Banner

AFNetworking 3.0

With the launch of iOS 7 Apple introduced a new method for networking named NSURLSession. However there exist a better alternative to consider – The popular third-party library for iOS, OS X, watchOS and tvOS called “AFNetworking”.
The latest library AFNetworking 3.0 not only includes all the great features provided by NSURLSession, but also has a lot of cool new features up its sleeves- like serialization, reachability support, UIKit integration. It supports JSON, XML and pList (Property List). However with the release of AFNetworking 3.0 in iOS 9, Apple decided to remove all support for the NSURLConnection method, which is now deprecated. Therefore if your project was built using NSURLConnection APIs, then it is now advisable to replace them with NSURLSession based APIs.
Today we will use the AFHTTPRequestOperation and see how AFNetworking 3.0 has evolved from its predecessor AFNetworking 2.0.

For AFNetworking 2.0

NSString *string = [NSString stringWithFormat:@"some_URL.json"];
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *myOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[myOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *myOperation, id responseObject)
{
// . . . when request succeeds
}failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// . . . if something goes wrong
}];
[myOperation start]; //in AFNetworking 2.0 we have to explicitly start the operation

For AFNetworking 3.0

NSURL *URL = [NSURL URLWithString:@"some_URL.json"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject)
{
// . . . when request succeeds
}failure:^(NSURLSessionTask *myOperation, NSError *error)
{
// . . . if something goes wrong
}];

Princeton IT is the leading mobile application development company in USA. Get in touch!