Vivek2012
Vivek2012

Reputation: 772

How to upload and download data on server in iphone(ios)

I am working on application called "Messanger".

My task is to upload and download data from and to a server .. I am new to this, so I don't know how to do it.

  1. I want to share data with server (upload)
  2. I want to get data from server (download)

Can anyone help me with this ?? I need code for this.

Thanks in Advance ..

Upvotes: 2

Views: 4434

Answers (2)

Nekto
Nekto

Reputation: 17877

You can use classes provided in official sdk.

0) Common part.

First of all you should create NSURLRequest. For example, NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"apple.com"]];

1) Uploading data.

When you want to send some data you can use this in following way (for example, sending xml):

NSString *message = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" ?>\n<parameters></parameters>"];
NSData* msgData = [message dataUsingEncoding:NSUTF8StringEncoding];
NSString *msgLength = [NSString stringWithFormat:@"%d",[msgData length]];

[request addValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request addValue:msgLength                         forHTTPHeaderField:@"Content-Length"];
[request setValue:@"iOsApp"                         forHTTPHeaderField:@"User-agent"];

[request setHTTPMethod:@"POST"];
[request setHTTPBody:msgData];
[message release];

2) Downloading data.

Now you should start connection:

[NSURLConnection connectionWithRequest:request delegate:self];

3) implement needful delegate methods. And at last you should implement that delegate methods that you would need. For example, in method - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data you will merge received data, in methods - (void)connectionDidFinishLoading:(NSURLConnection *)connection and - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error you should process received data.

For complete list of all methods that you could implement to receive more information about your internet connection and handle different process (like authentication, response code and other) read official documentation : NSURLConnection

Upvotes: 8

Andrey Gershengoren
Andrey Gershengoren

Reputation: 916

You can use the ASIHttpRequest library. There are a lot of examples, hope it will help you

Upvotes: 2

Related Questions