Episode #6

AFNetworking

12 minutes
Published on March 8, 2012
AFNetworking is a simple-yet-powerful toolkit for making HTTP requests dead simple. It is my current go-to framework for writing API clients in iOS applications.

Sending a simple JSON Request

NSURL *url = [NSURL URLWithString:@"https://search.twitter.com/search.json?q=ipad"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation 
    JSONRequestOperationWithRequest:request 
                            success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
                                NSLog(@"Tweets: %@", [json valueForKeyPath:@"results"]);
                            } failure:nil];

[operation start];

Creating an API Client

// BeersApiClient.h
# import "AFNetworking.h"
@interface BeersApiClient : AFHTTPClient

+ (id)sharedInstance;

@end
// BeersApiClient.m
#import "BeersApiClient.h"

@implementation BeersApiClient

+ (id)sharedInstance {
    static BeersApiClient *__sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        __sharedInstance = [[BeersApiClient alloc] initWithBaseURL:
            [NSURL URLWithString:BeersAPIBaseURLString]];
    });

    return __sharedInstance;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self) {
        //custom settings
        [self setDefaultHeader:@"x-api-token" value:BeersAPIToken];


        [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    }

    return self;
}

@end

Consuming the Beers API Client

[[BeersApiClient sharedInstance] getPath:@"beers.json" parameters:nil 
                                 success:^(AFHTTPRequestOperation *operation, id response) {
                                     NSLog(@"Response: %@", response);
                                     NSMutableArray *results = [NSMutableArray array];
                                     for (id beerDictionary in response) {
                                         Beer *beer = [[[Beer alloc] initWithDictionary:beerDictionary] autorelease];
                                         [results addObject:beer];
                                     }
                                     self.results = results;
                                     [self.tableView reloadData];
                                 }
                                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                     NSLog(@"Error fetching beers!");
                                     NSLog(@"%@", error);                                     
                                 }];
Want more? Subscribers can view all 587 episodes. New episodes are released regularly.

Subscribe to get access →

Source Code

View on GitHub Download Source