开发者

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

I am working on application called "Messange开发者_运维问答r".

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜