NSUrlConnection 网络下载

//频繁调用每次带回来一部分数据,如果此处创建一个全局变量nsmutableData 则必然会导致nsmutableData越来越大,内存暴增
//解决办法: 每次获取到一部分数据后,就将这部分数据写入到沙盒,并释放掉
//NSFileHandle 可以实现对文件的读取 写入 更新
// stringByAppendingPathComponent 这个函数会自动创建文件层级
- (void)connection:(NSURLConnection )connection didReceiveData:(NSData )data{
// [_globalData appendData:data];
NSLog(@”%@”,_globalData);
[_fileHandler seekToEndOfFile];//指定写入位置,文件最后
[_fileHandler writeData:data];//向沙盒写入数据
_currentLength += data.length;
_progressView.progress = 1.0 * _currentLength / _fileLength;
_label.text = [NSString stringWithFormat:@”%.2f%%”,_currentLength * 100.0 / _fileLength];
NSLog(@”%s”,func);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@”%@”,_globalData);
[_fileHandler closeFile];
_fileHandler = nil;
_currentLength = 0;
_fileLength = 0;
// NSLog(@”%s”,func);
}
- (void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response{
_fileLength = response.expectedContentLength;
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];//自动添加/stringByAppendingPathComponent
NSLog(@”file downloadto %@”,path);
// NSString *secPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@”“];

//创建一个空的文件到沙盒中
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
_fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
NSLog(@"%s",__func__);

}
- (void)connection:(NSURLConnection )connection didFailWithError:(NSError )error{

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值