AFNetworking 2.0 Tutorial

Learn how to easily get and post data from a web service in iOS in this AFNetworking 2.0 tutorial. By Joshua Greene.

Leave a rating/review
Save for later
Share
You are currently viewing page 4 of 4 of this article. Click here to view the first page.

I’m Not Dead Yet!

You might have noticed that this external web service can take some time before it returns with data. It’s important to provide your users with feedback when doing network operations so they know the app hasn’t stalled or crashed.

Luckily, AFNetworking comes with an easy way to provide this feedback: AFNetworkActivityIndicatorManager.

In WTAppDelegate.m, add this import just below the other:

#import "AFNetworkActivityIndicatorManager.h"

Then find the application:didFinishLaunchingWithOptions: method and replace it with the following:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    return YES;
}

Enabling the sharedManager automatically displays the network activity indicator whenever a new operation is underway. You won’t need to manage it separately for every request you make.

Build and run, and you should see the little networking spinner in the status bar whenever there’s a network request:

Now there’s a sign of life for your user even when your app is waiting on a slow web service.

Downloading Images

If you tap on a table view cell, the app takes you to a detail view of the weather and an animation illustrating the corresponding weather conditions.

That’s nice, but at the moment the animation has a very plain background. What better way to update the background than… over the network!

Here’s the final AFNetworking trick for this tutorial: AFHTTPRequestOperation can also handle image requests by setting its responseSerializer to an instance of AFImageResponseSerializer.

There are two method stubs in WeatherAnimationViewController.m to implement. Find the updateBackgroundImage: method and replace it with the following:

- (IBAction)updateBackgroundImage:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"https://koenig-media.raywenderlich.com/uploads/2014/01/sunny-background.png"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFImageResponseSerializer serializer];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        self.backgroundImageView.image = responseObject;
        [self saveImage:responseObject withFilename:@"background.png"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       
        NSLog(@"Error: %@", error);
    }];
    
    [operation start];
}

This method initiates and handles downloading the new background. On completion, it returns the full image requested.

In WeatherAnimationViewController.m, you will see two helper methods, imageWithFilename: and saveImage:withFilename:, which will let you store and load any image you download. updateBackgroundImage: calls these helper methods to save the downloaded images to disk.

Find the deleteBackgroundImage: method and replace it with the following:

- (IBAction)deleteBackgroundImage:(id)sender
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"WeatherHTTPClientImages/"];
	
    NSError *error = nil;
    [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
    
    NSString *desc = [self.weatherDictionary weatherDescription];
    [self start:desc];
}

This method deletes the downloaded background image so that you can download it again when testing the application.

For the final time: build and run, download the weather data and tap on a cell to get to the detailed view. From here, tap the Update Background button. If you tap on a Sunny cell, you should see this:

Where To Go From Here?

You can download the completed project from here.

Think of all the ways you can now use AFNetworking to communicate with the outside world:

  • AFHTTPOperation with AFJSONResponseSerializer, AFPropertyListResponseSerializer, or AFXMLParserResponseSerializer response serializers for parsing structured data
  • UIImageView+AFNetworking for quickly filling in image views
  • Custom AFHTTPSessionManager subclasses to access live web services
  • AFNetworkActivityIndicatorManager to keep the user informed
  • AFHTTPOperation with a AFImageResponseSerializer response serializer for loading images

The power of AFNetworking is yours to deploy!

If you have any questions about anything you’ve seen here, please pay a visit to the forums to get some assistance. I’d also love to read your comments!