My Blog List

Friday 3 May 2013

Consuming Webservices & Parsing JSON Response Tutorial(iOS) :Part 1


Hi Folks ,
Today, I want to make a demonstration of fetching data from web servers by using NSURLConnection on objective-c platform.
What we are going to do?
We are going to create an application that will demonstrate you guys to make a GET  request with NSURLConnection. After that, the retrieved data will be shown in UiTableview .It would be basically my favorite Artist name and his image .
For this tutorial i am going to consume one WCF web service ,thanks to one of my colleague to helping me :-)

API :http://182.72.47.242:49/RpManageCommon/GetArtistPhotos
Retrieved Data would be JSON format shown as below:

{"list":[{"image":"http:\/\/182.72.47.242:49\/images\/dy.png","name":"Dy"},{"image":"http:\/\/182.72.47.242:49\/images\/eminem.png","name":"Eminem"},{"image":"http:\/\/182.72.47.242:49\/images\/enrique.png","name":"Enrique"},{"image":"http:\/\/182.72.47.242:49\/images\/fiftycent.png","name":"Fiftycent"},{"image":"http:\/\/182.72.47.242:49\/images\/pitbull.png","name":"Pitbull"}]}

Now first of all create a new project on Xcode as a single view application. You may use any other of them however the project that I have started with was single view application.
Put UiTableView onto a xib, and make the bindings related to the view controller’s header file.
Open your view controller’s header class. In my example it is called “ViewController.h” and modify it as like as below.

import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
NSMutableData *receivedData;
}
@property (nonatomic, assign) IBOutlet UITableView *myTableView;
-(void)connectWebserviceSync;
@end

What we have done in here, we have created UITableView, and 1 NSMutableData object. One of the most important thing in here is that our view controller has implemented NSURLConnectionDataDelegate. Whenever our connection object start to fetching from a web page, if the delegate of our connection object is set to this view controller, it will call delegate methods to warn our view controller about the state of connection. Now let’s make some coding over view controller’s .m file.
First of all, I would like to implement the connectWebServiceSync method. Whenever  application will enter in ViewWillAppear Mode  it will call connectWebServiceSync method.
connectWebServiceSync  simply create NSURLConnection request and execute it.
Modify your .m as shown below


-(void)viewWillAppear:(BOOL)animated
{
//call webservice here
[self connectWebserviceSync];
}

-(void)connectWebserviceSync
{
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://182.72.47.242:49/RpManageCommon/GetArtistPhotos"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
// receivedData is an instance variable declared elsewhere.
receivedData = [[NSMutableData data] retain];
} else {
// Inform the user that the connection failed.
NSLog(@"connection failed");
}
}



Here I create url, and afterwards a request with respect to instance of url. These are the same procedures for every requests
The tricky part , the delegation, comes into play at this time. The folks at Apple has created a simple way to deal with the states of connection by using delegation structure.There are actually lots of delegate methods in NSURLConnectionDataDelegate however, just only 3 of them is required to be implemented in class. Those are;
this method might be calling more than one times according to incoming data size

*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
}
/*
if there is an error occured, this method will be called by connection
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{

NSLog(@"%@" , error);
}

/*
if data is successfully received, this method will be called by connection
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
 NSString *responseString = [[[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding] autorelease];   NSLog(@"Succeeded! Received JSON String %@ ",responseString);
// release the connection, and the data object
    [connection release];
[receivedData release];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data this method is called more than ones if the data returned by server is huge. NSURLConnection is clever enough how to split and whenever it gets any kind of data it calls this method from bound delegate class.
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error this method is called if something is abnormally going on during the connection.
-(void)connectionDidFinishLoading:(NSURLConnection *)connection this method is called when connection finishes its job successfully. All the actions after fetching data from server can be done here. In our example, we have filled our data into our object “receivedData”. Now that, we can  convert our data into string with UTF8 encoding, and then can store it somewhere or Log it.
For this tutorial i just used NSLog to print json response.If you are implementing above code hit run and look into your console for output.



What to do next?
We have Raw JSON string as a response.now we have to parse that raw JSON response and populate data over UITableView view
to be continued.....

1 comment:

  1. Ciitnoida provides Core and java training institute in

    noida
    . We have a team of experienced Java professionals who help our students learn Java with the help of Live Base Projects. The object-

    oriented, java training in noida , class-based build

    of Java has made it one of most popular programming languages and the demand of professionals with certification in Advance Java training is at an

    all-time high not just in India but foreign countries too.

    By helping our students understand the fundamentals and Advance concepts of Java, we prepare them for a successful programming career. With over 13

    years of sound experience, we have successfully trained hundreds of students in Noida and have been able to turn ourselves into an institute for best

    Java training in Noida.

    java training institute in noida
    java training in noida

    ReplyDelete