MacPandit

The secret of success is making your vocation your vacation

Posting data to url in Objective-C April 16, 2009

Filed under: iPhone — Pandit @ 3:14 am


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:@”http://www.abcde.com/xyz/login.aspx”%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.


if(conn)
{
NSLog(@”Connection Successful”)
}
else
{
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 these ads
 

12 Responses to “Posting data to url in Objective-C”

  1. rahul Says:

    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 Says:

    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. Rahul Says:

    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. rahul Says:

    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. rahul Says:

    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:

    http://clients.hwsdemos.com/rahul053/iphone/insert.php?username=yourname&password=yourpassword

    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 Says:

    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 “www.macpandit.com” .

  7. GAMPSLASK Says:

    Hello, I want to say hi everyone.
    test

  8. Pooja Rusia Says:

    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.

    thanx
    pooja

  9. rahul Says:

    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

    Thanks
    Sandra Dalene VanAlstine

  11. Arun Says:

    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. Ondrej Says:

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


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 )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.