Posting data to url in Objective-C

Here, I am leaving some important notes that you can use in your code for sending data for login page link or a particular forum link using objective C. Also you can use this for posting comments or posting posts to a particular forum or url link.

I am mentioning all the relative apis with the dummy urls for your understanding the whole procedure. Follow the points as per mentioned below

For sake of understanding , take an example of sending username and password to your login page. To do this follow the following steps.

1. set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@”&Username=%@&Password=%@”,@”username”,@”password”];

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

You need to send the actual length of your data. Calculate the length of the post string.

NSString *postLength = [NSString stringWithFormat:@”%d”,[postData length]];

3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string.
Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@””%5D%5D%5D;

Now, set HTTP method (POST or GET).
Write this lines as it is in your code.

[request setHTTPMethod:@”POST”];

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@”Content-Length”];

Also set the Encoded value for HTTP header Field.

[request setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Current-Type”];

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

NSLog(@”Connection Successful”)
NSLog(@”Connection could not be made”);

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

Above method is used to receive the data which we get using post method.

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

This method , you can use to receive the error report in case of connection is not made to server.

– (void)connectionDidFinishLoading:(NSURLConnection *)connection

The above method is used to process the data after connection has made successfully.

Have a Happy Coding !


About Pandit

Mac OS, iPhone SDK, Applescript, FileMaker.

Posted on April 16, 2009, in iPhone. Bookmark the permalink. 21 Comments.

  1. hi,
    I am rahul bhargava and i am very new in iphone application development. i implemented your code into my program and when i m running this code in every case it is returning connection successful even when url is not valid.

    Please suggest me solution .

  2. Pakhurde Pandit

    URLConnection object will request the url to web and you will always get the response even if the url is not valid.

    “If” condition which I am using in the code is just checking the conn and conn is always having the data. So it will give connection successful always. I just written it for understanding purpose. Connection is successful or not depends on the response that we get in URLConnection object.

    You need to check the response in conn object. That you can check with the one error delegate method(didFailWithError).

  3. Thanks You sir for replying soon.
    I will try it and if i will face any more problem i will discuss with you.
    Thanks Again

  4. Hello Sir,
    sir i have executed your code in file named mainView.m on a button click event, but its giving error in step 5 i.e. error:’connection’ undeclared(first use in this function) and error:syntax error before’:’ token.

    And i wish to know how could i print that connection error in log please give me syntax.

  5. Sir , i wish to plan,to make a iphone project which can do the following internally
    i have a link on my server which can be accessed from any where link:
    i wish to call this link on button click with variable username and password and after submitting it it will store username and password to my database and that changes can be viewed by me on my web server.(i don’t wish to open that link on iphone i just wish everything internally).
    so what procedure i will have to write or follow or just modifying your above code it is possible .
    I am waiting for your positive reply.

  6. Pakhurde Pandit

    Here, you are misunderstanding the concept. Url is used to process the data , not for storing the data in the database. Other thing is that the link which you have mentioned is a “Query string”. Code mentioned in this post is about URL. There is significant difference between URL and Query string. Do googling on this , you will find number of differences between these two.

    In short , difference between URL and Query string is in Query string you can send the data internally from that query string itself but in case of URL, you have to send the data externally by HTTP connection using GET or POST methods.

    See my next post on this. In that you will understand how to send data using Query string.

    For my next posts please visit my new site “” .

  7. Hello, I want to say hi everyone.

  8. Hello sir,
    i am developing a iphone application and i want to retrive the result from the external site(live site) by passing some
    parameter to the site .so how can i retrive the output from there.
    how can i establish the connnection between my application to the external site (live site).
    Please give me Reply as soon as possible.


  9. Hi,

    How to make sure that the connection is established and how to receive the response data.

  10. Sandra Dalene VanAlstine – Wanted to introduce myself

    Sandra Dalene VanAlstine

  11. Could you please send example of 3 option.My requirment is firstname,secondname,email entered into mobile native application and press send button it will go to server(web server listing mode) .Once the data from iphone , it will store in database.

    So which option will be matched for me.

  12. I want to sa hi as well … HI! :)))

  13. Hi,
    i used the code mentioned above to send a string to a webpage created in jsp, which will print the text send by me. but it is not working. plz help me to send a text to jsp page and print it thr only..

  14. what i did is this now what is happening is that i m getting an error when i use post method that invalid username n password and when use get method it response is nothing :S .. bdw i m displaying response in UITextView .. please tell me whats wrong 😦

    NSString* username = usernameField.text;
    NSString* pass = passwordField.text;

    [usernameField resignFirstResponder];
    [passwordField resignFirstResponder];

    NSString *post = [[NSString alloc] initWithFormat:@”&UserName=%@&Password=%@”,username,pass];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

    NSString *postLength = [NSString stringWithFormat:@”%d”, [postData length]];

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

    [theRequest setValue:username forHTTPHeaderField:@”UserName”];
    [theRequest setValue:pass forHTTPHeaderField:@”Password”];
    [theRequest setHTTPMethod:@”GET”];
    [theRequest setValue:postLength forHTTPHeaderField:@”Content-Length”];
    [theRequest setValue:@”application/x-www-form-urlencoded” forHTTPHeaderField:@”Current-Type”];
    [theRequest setHTTPBody:postData];

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

    if( theConnection )
    webData = [[NSMutableData data] retain];


    [usernameField resignFirstResponder];
    [passwordField resignFirstResponder];
    //passwordField.text = @”abc”;

    loginIndicator.hidden = FALSE;
    [loginIndicator startAnimating];

    loginButton.enabled = FALSE;
    //nameInput.text = nil;
    //passInput.text = nil;

    -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    [webData setLength: 0];
    -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

    [webData appendData:data];
    -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

    [connection release];
    [webData release];
    -(void)connectionDidFinishLoading:(NSURLConnection *)connection

    NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    status.text = loginStatus;
    [loginStatus release];

    loginIndicator.hidden = TRUE;
    [connection release];
    [webData release];

  15. plz 2 met u all, thx 4 article, good sample

  16. What if we have https, i have tried using delegate methods doesnt work, any suggestions.

  17. Sanchit Singh

    I tried it, It worked perfectly.

  18. While posting the encrypted string ‘+’ is getting replaced by a space. Any suggestions ?

  19. This really helped me alot…..thank you

  20. Hi…….
    i hit the url with the following URL but i did not get any data in response
    NSString *restCallString = [NSString stringWithFormat:@””];

    NSURL *apiUrl=[[NSURL alloc] initWithString:restCallString];

  21. give an alternative to get data from this JSON API

Leave a Reply

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

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

%d bloggers like this: