How to use AFNetworking library for JSON parsing ?

Hello everyone, In my last app , i have used AFNetworking library for JSON parsing, and believe me its really very easy. So i decided to share part of code which we used for parsing. Below are the steps.

1) First we need to add AFNetworking library in our Project, or you can also drag and drop AFNetworking folder into the project.

2) Next open the header file .h where you want to do parsing and add the following lines

#import “AFHTTPClient.h”

#import “AFHTTPRequestOperation.h”

3) Click on .m file for the class and add the following lines of code in ViewDidLoad method

    NSURL *url = [[NSURL alloc] initWithString:@”HERE YOU WILL NEED TO ADD THE URL FOR  JSON WEB SERVICES”]; 

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

        // HERE IF THE REQUEST IS SUCCESSFUL YOU WILL GET RESPONSE IN JSON. Below is the sample which i have used.

    self.movies = [JSON valueForKey:@”appointed_service”]; // HERE self.movies is NSArray and we get all the information in array

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {

        NSLog(@”Request Failed with Error: %@, %@”, error, error.userInfo);

    }];

    [operation start];

Now we can check with the array with all the information which we retrieved and used that later. Below is the sample

    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];

    cell.textLabel.text = [movie objectForKey:@”apt_service_name”];

    cell.detailTextLabel.text = [movie objectForKey:@”apt_service_tech_name”];

    NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:@”apt_service_image_url”]];

    [cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@”placeholder”]];

I have got all the details in UITableView with the above code.

Thats the only thing which we need to implement for AFNetworking and JSON parsing will be very easy

Hope you like the tutorial, Feedback are always welcome. Cheers, Have a great day ahead.

About these ads

4 thoughts on “How to use AFNetworking library for JSON parsing ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s