iOS-实现文件上传下载

iOS开发中会经常用到文件上传下载的功能,这篇文件将介绍一下使用asp.net webservice实现文件上传下载。
首先,让我们看下文件下载。
这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。
同步下载文件:

  NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil
error:&error];
/* 下载的数据 */
if (data != nil){
NSLog(@"下载成功");
if ([data writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
NSLog(@"保存成功.");
}
else
{
NSLog(@"保存失败.");
}
} else {
NSLog(@"%@", error);
}


异步下载文件:

- (void)viewDidLoad
{
[super viewDidLoad];
//文件地址
NSString *urlAsString = @"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSMutableData *data = [[NSMutableData alloc] init];
self.connectionData = data;
[data release];
NSURLConnection *newConnection = [[NSURLConnection alloc]
initWithRequest:request
delegate:self
startImmediately:YES];
self.connection = newConnection;
[newConnection release];
if (self.connection != nil){
NSLog(@"Successfully created the connection");
} else {
NSLog(@"Could not create the connection");
}
}


- (void) connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error{
NSLog(@"An error happened");
NSLog(@"%@", error);
}
- (void) connection:(NSURLConnection *)connection
didReceiveData:(NSData *)data{
NSLog(@"Received data");
[self.connectionData appendData:data];
}
- (void) connectionDidFinishLoading
:(NSURLConnection *)connection{
/* 下载的数据 */

NSLog(@"下载成功");
if ([self.connectionData writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {
NSLog(@"保存成功.");
}
else
{
NSLog(@"保存失败.");
}

/* do something with the data here */
}
- (void) connection:(NSURLConnection *)connection
didReceiveResponse:(NSURLResponse *)response{
[self.connectionData setLength:0];
}

- (void) viewDidUnload{
[super viewDidUnload];
[self.connection cancel];
self.connection = nil;
self.connectionData = nil;
}


从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值