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

20 thoughts on “NSURLConnection basics for iOS beginners?

  1. I do consider all of the concepts you have presented on your post. They’re very convincing and can certainly work. Nonetheless, the posts are too brief for starters. May just you please prolong them a little from subsequent time? Thanks for the post.

  2. hello yuvaraj….. really your work guides me to learn more things….. thank you so much…… can u plz send some basic material for iOS….. am new for iOS…..

    • Hi Divya,
      Many free tutorials are in Google to guide you in iOS development. And also Apple providing many documents for every classes in iOS development. I will send you some useful tutorials and apple document links to your mail. Thanks for your visit and comments. Looking forward more comments from you. Thanks.

  3. Thanks. your article.

    But, I have Question to you.
    if I send to some url and I receive “.jsp” file
    (file contents is XML)
    Where I can receive file and
    How can I parse received file?

    Sorry, My bad Englsh…

    PS> I’m beginning iPhone programming pew days ago…
    and I do not know http communication process…

  4. hello sir,i am new in iphone programming.your tutorial was very helpfull for me it was very simple,by implementing the same i got connected to the server But now i want to send data to the server through URL so how can i do the same.
    it may be a stupid question..

  5. Pingback: Sending an HTTP POST request on iOS – Kamy Academy

Leave a reply to amedar consulting Cancel reply