AFNetworking Crash Course

In this AFNetworking tutorial, i am going to explain more about the AFNetworking functionality. In my previous AFNetworking tutorial i just only given an introduction to AFNetworking. In the cause of NSURLConnection provided by apple is bit difficult to understand in the case of beginner, but  AFNetworking framework is so simple and its api are more powerful too.

[box] AFNetworking is also incredibly popular – it won our Reader’s Choice 2012 Best iOS Library Award. So it’s time we wrote a tutorial to show you how to effectively use it in your apps.[/box]

AFNetworking contain all the major api’s what we need to communicate with the network and do the network operations in iOS 6. AFNetworking will never freeze the user interface of the application, when you do the network calls. AFNetworking also successfully implemented the block programing concept too. So this will help the developer to accelerate the iOS application  development speed.

This tutorial will help you to get a perfect understanding about the AFNetworking api and its components. Along with the way we will build a twitter tweets search application using AFNetworking. So let’s get start!

Step 1 :

Download AFNetworking source code from github.

Step 2 :

Create a new project named Twitter Example and also create a group folder AFNetworking inside the project, drag and drop the AFNetworking source files.
AFNetworking

You can see “MasterViewController.xib” it is the master user interface, in that we need to add a UITableView search box controller.Clean the unnecessary code’s from the MasterViewController.h and MasterViewController.m file.
next we need to define the search url of twitter in the MasterViewController,because this url is used for the initial call of AFNetworking.

#define SEARCH_URL @"http://search.twitter.com/search.json?q="

when you search for the tweets in twitter about iPhone it will return a json data

{
    "completed_in": 0.099,
    "max_id": 324767909085863940,
    "max_id_str": "324767909085863936",
    "next_page": "?page=2&max_id=324767909085863936&q=iPhone",
    "page": 1,
    "query": "iPhone",
    "refresh_url": "?since_id=324767909085863936&q=iPhone",
    "results": [
        {
            "created_at": "Thu, 18 Apr 2013 06:14:38 +0000",
            "from_user": "naatin0827",
            "from_user_id": 1333365348,
            "from_user_id_str": "1333365348",
            "from_user_name": "つんちょ",
            "geo": null,
            "id": 324767909085863940,
            "id_str": "324767909085863936",
            "iso_language_code": "ja",
            "metadata": {
                "result_type": "recent"
            },
            "profile_image_url": "http://a0.twimg.com/profile_images/3509848077/126e76e7749fff046964fc2c2c13609a_normal.jpeg",
            "profile_image_url_https": "https://si0.twimg.com/profile_images/3509848077/126e76e7749fff046964fc2c2c13609a_normal.jpeg",
            "source": "<a href="http://twitter.com/download/iphone">Twitter for iPhone</a>",
            "text": "かわきたのiPhoneのっとり〜( ´ ▽ ` )ノ"
        },
        {
            "created_at": "Thu, 18 Apr 2013 06:14:37 +0000",
            "from_user": "ShawnDoee_BH2T",
            "from_user_id": 428765499,
            "from_user_id_str": "428765499",
            "from_user_name": "#269 $wampGattaz",
            "geo": null,
            "id": 324767908154732540,
            "id_str": "324767908154732544",
            "iso_language_code": "en",
            "metadata": {
                "result_type": "recent"
            },
            "profile_image_url": "http://a0.twimg.com/profile_images/3375683870/d83969c609c9dcc04c27d10ac4e469b7_normal.jpeg",
            "profile_image_url_https": "https://si0.twimg.com/profile_images/3375683870/d83969c609c9dcc04c27d10ac4e469b7_normal.jpeg",
            "source": "<a href="http://twitter.com/download/iphone">Twitter for iPhone</a>",
            "text": "

So we need to create User class to hold the necessary information.The user class will be look like this

@interface User : NSObject

@property(strong)NSString *UserName;
@property(strong)NSString *TweetName;
@property(strong)NSString *UserProfileIcon;
@end

@implementation User
@synthesize UserName,TweetName,UserProfileIcon;
@end

we are all set for implementing the twitter tweet search. so we need to create a function listTweets.

-(void *)listTweets:(NSString *)username{
    [tweets removeAllObjects];

    //AFNetworking operation code
    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SEARCH_URL,username]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                                                        NSLog(@"Json recived");

                                                        [self processData:JSON];

                                                    }
                                                    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                                     message:[NSString stringWithFormat:@"%@",error]
                                                                                                    delegate:nil
                                                                                           cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                                        [av show];
                                                    }];

    [operation start];

    return nil;

}

now we need to process the json data what is get after the AFNetworking operation.

-(void)processData:(NSDictionary *)json{

    NSMutableArray *results =[json valueForKey:@"results"];
    NSLog(@"%d",results.count);
    for (id key in results) {
        User *user =[User new];
        user.UserName=[key valueForKey:@"from_user"];
        user.Tweet=[key valueForKey:@"text"];
        user.UserProfileIcon=[key valueForKey:@"profile_image_url"];
        [tweets addObject:user];

    }
     [self.tableView reloadData];
}

Now we need to implement the functionally of search for twitter tweets and showing activity indicator.final code will be look like this.

//
//  MasterViewController.m
//  Twitter Example
//
//  Created by safil sunny on 18/04/13.
//  Copyright (c) 2013 safil sunny. All rights reserved.
//
#define SEARCH_URL @"http://search.twitter.com/search.json?q="
#import "MasterViewController.h"
#import "AFNetworking.h"
#import "User.h"
@interface MasterViewController () {

    NSMutableArray *tweets;
    IBOutlet UISearchBar *searchBox;
    BOOL searching;
    UIActivityIndicatorView *activityIndicator;
}
@end

@implementation MasterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Master", @"Master");
    }
    return self;
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if ( ([searchText length] >= 3 )&& (!searching)) {
        [self listTweets:searchText];

    }
}

-(void *)listTweets:(NSString *)username{
    [activityIndicator startAnimating];
    searching=TRUE;
    [tweets removeAllObjects];
    NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",SEARCH_URL,username]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
                                                    success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                                                        NSLog(@"Json recived");

                                                        [self processData:JSON];

                                                    }
                                                    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                                                        UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                                     message:[NSString stringWithFormat:@"%@",error]
                                                                                                    delegate:nil
                                                                                           cancelButtonTitle:@"OK" otherButtonTitles:nil];
                                                        [av show];
                                                    }];

    [operation start];

    return nil;

}

-(void)processData:(NSDictionary *)json{

    NSMutableArray *results =[json valueForKey:@"results"];
    NSLog(@"%d",results.count);
    for (id key in results) {
        User *user =[User new];
        user.UserName=[key valueForKey:@"from_user"];
        user.Tweet=[key valueForKey:@"text"];
        user.UserProfileIcon=[key valueForKey:@"profile_image_url"];
        [tweets addObject:user];

    }

    searching=FALSE;

    [searchBox resignFirstResponder];
    [activityIndicator stopAnimating];
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    tweets=[[NSMutableArray alloc] initWithObjects: nil];

    activityIndicator =[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(self.tableView.frame.size.width/2, self.tableView.frame.size.height/4, 50, 50)];
    [self.view addSubview:activityIndicator];
    [activityIndicator setBackgroundColor:[UIColor redColor]];

	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [tweets count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }

    User *user =[tweets objectAtIndex:indexPath.row];
    cell.textLabel.text =user.UserName;
    cell.detailTextLabel.text=user.Tweet;
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{

}

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}

@end

you can download the entire AFNetworking source code from here

AFNetworking

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Downloading Images using AFImageRequestOperation
In the case of AFNetworking we can download image files using AFImageRequestOperation.Here’s the final AFNetworking trick for this tutorial: AFImageRequestOperation. Like AFJSONRequestOperation, AFImageRequestOperation wraps an HTTP request that expects some kind of image.

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:user.UserProfileIcon]];
    AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
                                                                              imageProcessingBlock:nil
                                                                                           success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                                                                                               cell.imageView.image=image;

                                                                                           }
                                                                                           failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                                                                                               NSLog(@"Error %@",error);
                                                                                           }];
    [operation start];

AFNetworking

you can download the image view integrated AFImageRequestOperation example from here.

if you have any doubts in integrating AFNetworking just replay here or you can report AFNetworking bug here
Credits
[box type=”shadow”]

AFNetworking was created by Scott Raymond and Mattt Thompson in the development of Gowalla for iPhone.

AFNetworking’s logo was designed by Alan Defibaugh.

And most of all, thanks to AFNetworking’s growing list of contributors.
Follow AFNetworking on Twitter (@AFNetworking)
[/box]

No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *