简体   繁体   中英

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 ..

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM