1.小文件的下载方法
A.NSURL *url = [NSURLURLWithString:@"http://image2.sina.com.cn/ent/v/m/p/2005-11-11/U92P28T3D893697F329DT20051111200426.jpg"];
NSData *data = [NSDatadataWithContentsOfURL:url];
NSLog(@"%@",data);
B.[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueuemainQueue] completionHandler:^(NSURLResponse *_Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@"%@",data);
}];
C.[NSURLConnectionconnectionWithRequest:[NSURLRequestrequestWithURL:url] delegate:self];
2.获取文件大小的方法:两种方法:(nonnull NSURLResponse *)response -》response.expectedContentLength;
(NSHTTPURLResponse *)response -》[response.allHeaderFields[@"Content-Length"]floatValue];
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{
//(nonnull NSURLResponse *)response{
// _totalData = response.expectedContentLength;
_totalData = [response.allHeaderFields[@"Content-Length"]floatValue];
NSLog(@"%s,%lld",__func__,response.expectedContentLength);
}
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject];
NSString *file = [cachesstringByAppendingPathComponent:@"hahah.jpg"];
[self.responseDatawriteToFile:file atomically:YES];
self.responseData =nil;
#define WXYFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:@"hahah.jpg"]
//创建文件句柄对象
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:WXYFile];
//指定分段下载数据的写入位置
[handle seekToEndOfFile];
[handle writeData:data];
//关闭handle,下载完成后
[handle closeFile];
self.handle = nil;
self.contentLenght = [response.allHeaderField[@"Content-Length"]floatValue];
self.currentLenght += data.length;
self.progressView.progress = 1.0 * self.currentLenght / self.contentLength;