iOS Access webservices using NSURLConnection

Introduction

With geometric rate of progression in the mobile technology, almost each application is required to exchange data with the server. This aspect of an application is achieved using web services. Web services act as a middle ware between your server and front end client. This post will help you to access the webservices data using the predefined class in iOS framework i.e. NSURLConnection. This example demonstrates the application to connect with webservices SYNCHRONOUSLY. Will guide you to connecting with webservices using asynchronous connection in a separate post. So Let us begin!!!

PLEASE NOTE: You can download the whole source code from here – DOWNLOAD CODE

We will take a simple example to demonstrate this up.

The example consists of a TableView embedded in a NavigationController. The application connects to a public web service, in this case RottenTomatoes.com and loads the data to the table view as required. You will be required to signup with  website to generate an API Key and run the example code successfully.

Summary:

Main.storyboard – This file is a storyboard file for iOS which consists of a NavigationController with a table view embedded to it.

WSViewController.h – The header implementation file consisting of definitions to run the code successfully.

WSViewController.m – The implementation file consisting of the code to handle the request and accordingly display data to the user.

WSAppDelegate.h & WSAppDelegate.m  – The AppDelegate files for the application to manage the workflow and correct functioning of App.

Code Time:

Step 1: Prepare your application views to handle the code in the implementation file. With the introduction of storyboads in iOS 5 it takes very less effort to maintain the files for the View part of application.

Delete the view controller already created by default by Xcode.

Drag a TableViewController instance to the view and drop it.

Select the instance, go to Editor > Embed In > Navigation Controller. This will embed you current view into a NavigationController and making NavigationController as the InitialViewController.

Step 2: Refactor your code in .h file. Extend your class to UITableViewController and implement UITableViewDataSource, UITableViewDelegate and NSURLConnectionDataDelegate.

@interface WSViewController :
UITableViewController<UITableViewDataSource,UITableViewDelegate,
NSURLConnectionDataDelegate>

Step 3: Switch back to your main storyboard file.

Add the class name to property inspector.

Screen Shot 2013-12-01 at 6.04.30 pm

Step 4: Add the property declarations to the .h file

//Stores the values for the data that is returned from the webservice.
@property (strong,nonatomic) NSMutableData *wsData;
//Stores the values for the final results in an array.
@property (strong,nonatomic) NSMutableArray *results;
@property (strong,nonatomic) NSMutableDictionary *jsonData;

Now, time to add the code for connecting and rendering the data.

Step5: Switch to .m file.

Synthesize the properties declared in .h file.

@synthesize wsData;
@synthesize results;
@synthesize jsonData;

Now add the following code to your viewDidLoad to connect to the URL synchronously and fetch the data.

//Initiate the variables to store data to be used in the application.
self.jsonData = [NSMutableDictionary dictionary];
self.results = [NSMutableArray array];
self.wsData = [[NSMutableData alloc] init];

//Create the URL String using URI and API Key
NSString *uriString = [NSString stringWithFormat:@"%@%@",URI,API_KEY];

//Intial setup to make a call to webservice.
NSURL *url = [NSURL URLWithString:uriString];

//Create a request object to make a request to the URL.
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;

NSData *data = [NSURLConnection
sendSynchronousRequest:request
returningResponse:&response
error:&error];

if(error == nil)
{
[self.wsData appendData:data];
self.jsonData = (NSMutableDictionary *)[NSJSONSerialization
JSONObjectWithData:(NSMutableData *)self.wsData
options:NSJSONReadingMutableContainers
error:nil];

self.results = [self.jsonData
objectForKey:@"movies"];

}

In the above code, we have created a NSURL instance which consists of a URL that we are required to connect to fetch the data which is to be used as a datasource in our application.

NSURL instance is then wrapped in a NSURLRequest instance to be used for connecting and making a request using the NSURLConnection.

+ sendSynchronousRequest:returningResponse:error is a static method in NSURLConnection class that allows us to connect to the URL and fetch the response accordingly. It returns a NSData object.

To convert the data to JSON format we will be using the NSJSONSerialization class static method. It converts the NSData Object into a NSDictionary. Once done the data is ready to be used in the application.

Step 6: Implement the TableView Delegate and Datasource methods.

#pragma mark TableView Datasource Methods
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}

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

#pragma mark TableView Delegate Methods

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CELL_IDENTIFIER = @"WEBSERVICETABLECELL";

UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CELL_IDENTIFIER];

if(cell == nil)
{
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CELL_IDENTIFIER];
}

//Mainuplate data and set the cell text and image values.

NSDictionary *resultDictionary = [self.results objectAtIndex:indexPath.row];
NSDictionary *posterDictionary = [resultDictionary objectForKey:@"posters"];

cell.textLabel.text = [resultDictionary objectForKey:@"title"];

cell.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[posterDictionary objectForKey:@"thumbnail"]]]];
return cell;
}

Step 7: Run your code to check out the output. You will be able to see the output as the image provided below

Screen Shot 2013-12-01 at 6.21.10 pm

I hope you enjoyed the post, keep looking forward to more.

2 thoughts on “iOS Access webservices using NSURLConnection”

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s