一、下载的性能优化
1. 使用一个缓冲Data存储下载的数据,当缓冲的数据>500kb,将此缓冲数据写入文件,并且清除缓冲数据,以节约内存
//开始下载
- (IBAction)download:(id)sender {
if (!download) {
//创建URL
NSURL *url = [NSURL URLWithString:@"http://img31.mtime.cn/pi/2013/03/13/115558.26463213_1280X720.jpg"];
//创建请求NSURLRequest
NSURLRequest *repuest = [NSURLRequest requestWithURL:url ];
//创建NSURLConnection 对象 并发送异步请求;
[NSURLConnection connectionWithRequest:repuest delegate:self];
download = YES;
//创建文件
//取得字符串的URL
NSString *urlstring = url.absoluteString;
NSString *filename = urlstring.lastPathComponent;
_filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",filename];
[[NSFileManager defaultManager] createFileAtPath:_filePath contents:nil attributes:nil];
}
}
//1.服务响应头
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_bufferData = [[NSMutableData alloc] init];
NSHTTPURLResponse *httpresponse = (NSHTTPURLResponse *)response;
NSDictionary *fields = [httpresponse allHeaderFields];
NSNumber *length = [fields objectForKey:@"Content-Length"];
total = [length doubleValue ];
}
//数据的传输
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_bufferData appendData:data];
receiveTotal += data.length;
double progress = receiveTotal/total;
_progressview.progress = progress;
_progresslable.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
NSLog(@"接受了%d字节数据",data.length);
//4.判断缓冲的数据大小是否>500kb
if (_bufferData.length > 500*1000) {
[self appendFileData:_bufferData];
[_bufferData setData:nil];
}
}
//追加文件数据- (void)appendFileData:(NSData *)appData {
if (appData.length == 0 || _filePath.length == 0) {
return;
}
// 使用NSFileHandle写文件,此文件必须已经创建,NSFileHandle是不会创建文件的
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:_filePath];
//将文件的写入点,定位到文件的末尾
[fileHandle seekToEndOfFile];
[fileHandle writeData:appData];
//关闭文件
[fileHandle closeFile];
}