iOS 文件下载并保存到沙盒中

同步下载,如果内容过大时,不推荐,会阻塞UI

- (void)syncDownload

{

    NSString *path = @"http://lx.cdn.baidupcs.com/file/test.mp4"; //下载文件地址

    NSURL *url = [NSURL URLWithString:path];

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];

    NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];

    [self save:data];

}

- (void)save:(NSData *)data

{

    NSString *temp = NSTemporaryDirectory();

    

    NSFileManager *fm = [NSFileManager defaultManager];

 

    _path = [temp stringByAppendingPathComponent:@"test.mp4"];

 

    BOOL b = [fm createFileAtPath:_path contents:_data attributes:nil];

}

//异步下载

- (void)asyncDownload

{

    NSString *path = @"http://lx.cdn.baidupcs.com/file/test.mp4"; //下载文件地址

    NSURL *url = [NSURL URLWithString:path];

    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:url];

 

    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:selfstartImmediately:YES];

}

//实现异步下载代理

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{

    NSLog(@"error");

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{

    NSLog(@"response");

    recLenth = 0;//初始化接收到的长度

    _data = [[NSMutableData alloc] initWithCapacity:0];

    lenth = [response expectedContentLength];//获取下载内容总长度

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{

    [_data appendData:data];//接收到数据

    recLenth += [data length];

    float pro = (float)recLenth/(float)lenth;//计算下载进度0-1

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

{

    NSLog(@"finish");

    [self save:_data];

 

}


转载于:https://my.oschina.net/u/2361492/blog/653598

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值