NSURLConnection basics for iOS beginners?

Hi Friends,

In this post am going to describe about NSURLConnection webservice invoke. I don’t know so much on this. But, i would like to share what are the things i know.

When i enter into iOS development no one guide me just i started with Apple Documents. So am not well in iOS development but i know something.

Ok, just start this topic with requesting simple NSURLRequset to URLConnection.

Why have to use NSURLRequest and NSURLConnection.

NSURLRequest:
From Apple:

NSURLRequest objects represent a URL load request in a manner independent of protocol and URL scheme.
NSURLRequest encapsulates two basic data elements of a load request: the URL to load, and the policy to use when consulting the URL content cache made available by the implementation.
Yes, this is using to send URL request to our server via NSURLConnection. Mainly we are using NSURLRequest and NSURLConnection to interact with our Webserver.

NSURLConnection:
From Apple:

An NSURLConnection object provides support to perform the loading of a URL request. The interface for NSURLConnection is sparse, providing only the controls to start and cancel asynchronous loads of a URL request.
NSURLConnection’s delegate methods—defined by the NSURLConnectionDelegate Protocol protocol—allow an object to receive informational callbacks about the asynchronous load of a URL request. Other delegate methods provide facilities that allow the delegate to customize the process of performing an asynchronous URL load. These delegate methods are called on the thread that started the asynchronous load operation for the associated NSURLConnection object.

Ok we will start with sample code. May be it will show your some idea. But am not sure this code will work for you without modification and using your inputs.

In our Webservice call I worked on both GET and POST methods,

1. Using GET Method:

– (void)viewDidLoad
{
[super viewDidLoad];

NSString *urlString = [NSString stringWithFormat:@”http://sample.com/api/sample.php/Cars/list/loginToken/%@/Car_key/123RT67GDF/start_date/%@/end_date/%@”,loginToken,startDate,endDate];   //This is sample webservice url. Please replace it with your own and pass your valid parameters.

NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];

[theRequest addValue: @”application/x-www-form-urlencoded; charset=utf-8″ forHTTPHeaderField:@”Content-Type”];
[theRequest setHTTPMethod:@”GET”];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( connection )
{
mutableData = [[NSMutableData alloc] init];
}
}

2. Using POST Method:

– (void)viewDidLoad
{
[super viewDidLoad];

NSString *urlString = [NSString stringWithFormat:@”http://sample.com/api/sample.php/Cars/list/loginToken/%@/Car_key/123RT67GDF”,loginToken];  //This is sample webservice url. Please replace it with your own.

NSString *parameter = [NSString stringWithFormat:@”firstname=%@&lastname=%@&notes=%@”,firstName, lastName, notes]; //Parameter values from user.

NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest addValue: @”application/x-www-form-urlencoded; charset=utf-8″ forHTTPHeaderField:@”Content-Type”];
[theRequest setHTTPMethod:@”POST”];
[theRequest setHTTPBody:parameterData];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if( connection )
{
mutableData = [[NSMutableData alloc] init];
}
}

Now we have to add NSURLConnection Delegates in your project. Please find the delegates below,

#pragma mark –
#pragma mark NSURLConnection delegates

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[mutableData setLength:0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mutableData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[mutableData release];
[connection release];

// If we get any connection error we can manage it here…
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@”Alert” message:@”No Network Connection” delegate:self cancelButtonTitle:nil otherButtonTitles:@”OK”,nil];
[alertView show];
[alertView release];

return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
NSLog(@”Response Json : %@”, jsonString);

// You can do your functions here. If your repines is in XML you have to parse the response using NSXMLParser. If your response in JSON you have use SBJSON.
}

This is simple NSURLConnection for beginners. There is another two ways to pass request to the server like in XML and JSON. I will share the details by next post.

Thanks you so much for spending your valuable time with me.

I apologize for the grammatical and spelling errors.
Happy Coding!

Warm Regards,
Yuvaraj.M