Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write data to the web server from iPhone application?

I am looking forward for posting some data and information on the web server through my iPhone application. I am not getting the way to post data to the web server from iPhone sdk.

like image 246
Dipti Y W Avatar asked Dec 02 '10 10:12

Dipti Y W


People also ask

How does iOS app communicate with server?

At the basic level, the iphone communicates over the internet. The internet uses Internet Protocol, and there are two standard protocols built atop of IP: Transmission Control Protocol, and User Datagram Protocol. Each has it's own uses and functions. TCP/IP and UDP/IP make up the backbone of internet communication.

Can you run a Web server on iPhone?

Whether you're learning web development and want to host your own HTML files on your iPhone, or whether you just want to play around with a server without being restricted to using a laptop or a computer to install MAMP, your iPhone can do it for you.

Do you need a server for an iOS app?

Do you need a server for an app? The short answer to this question is yes – you will need some sort of server space in order to serve application content to customers.


1 Answers

It depends in what way you want to send data to the web server. If you want to just use the HTTP POST method, there are (at least) two options. You can use a synchronous or an asynchronous NSURLRequest. If you only want to post data and do not need to wait for a response from the server, I strongly recommend the asynchronous one, because it does not block the user interface. I.e. it runs "in the background" and the user can go on using (that is interacting with) your app. Asynchronous requests use delegation to tell the app that a request was sent, cancelled, completed, etc. You can also get the response via delegate methods if needed.

Here is an example for an asynchronous HTTP POST request:

// define your form fields here:
NSString *content = @"field1=42&field2=Hello";

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.example.com/form.php"]];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[content dataUsingEncoding:NSISOLatin1StringEncoding]];

// generates an autoreleased NSURLConnection
[NSURLConnection connectionWithRequest:request delegate:self];

Please refer to the NSURLConnection Class Reference for details on the delegate methods.

You can also send a synchronous request after generating the request:

[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

If you pass a NSURLResponse ** as returning response, you will find the server's response in the object that pointer points to. Keep in mind that the UI will block while the synchronous request is processed.

like image 83
Björn Marschollek Avatar answered Sep 22 '22 11:09

Björn Marschollek