NSUrlConnection 网络下载

来源:互联网 发布:淘宝劳保用品 编辑:程序博客网 时间:2024/05/29 07:38

//频繁调用每次带回来一部分数据,如果此处创建一个全局变量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{

}

原创粉丝点击