一,小文件下载:
1,NSData直接下载:(内部默认发送GET请求,但是只会在子线程,that‘s bad)
注意:这两种方法如果在下载过程中断网终止下载,那么重新下载需要从零开始,所以不适合大文件
不能监听下载进度
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [NSURL URLWithString:@"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png"];
//下载到内存中
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"%lu",(unsigned long)data.length);
});
2,向服务器发送请求下载:(手动发送GET请求)
NSURL *url = [NSURL URLWithString:@"http://192.168.1.100:8080/MJServer/resources/images/minion_01.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(@"%lu",data.length);
}];
二,单线程大文件下载:(可以监听下载进度)
1,非断点下载单线程下载,如下:
主要的API:(NSURLConnection异步方法,会自动开启异步线程,设置代理后可以通过代理方法监听事件并作出相应的处理)
[NSURLConnection connectionWithRequest:request delegate:self];
如下:
//1,发送请求
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURL URLWithString:@"http://w.x.baidu.com/alading/anquan_soft_down_all/14247"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//2,如果出错来到这里
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError");
}
//3,接受到响应,只会调用一次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [cachesPath stringByAppendingPathComponent:@"QQ影音.exe"];
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:file contents:nil attributes:nil];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:file];
self.handle = handle;
self.totalLength = response.expectedContentLength;
}
//4,开始接受数据,调用多次,这里创建句柄对象对数据分段存储(如果只有一个子线程可以用下面seekToEndOfFile方法,如果是多线程那么需要先创建一个等同整个原始文件大小的文件,然后在用[self.handle seekToFileOffset:offset]方法存储数据)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.handle seekToEndOfFile];
[self.handle writeData:data];
self.currentLength += data.length;
NSLog(@"下载进度是:%f",(double)self.currentLength/self.totalLength);
}
//5,存储完毕后关闭句柄,调用一次
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.handle closeFile];
self.handle = nil;
self.currentLength = 0;
self.totalLength = 0;
}
三,单线程的断点下载:
- (IBAction)btnClicked:(UIButton *)sender {
sender.selected = !sender.isSelected;
if (sender.selected) {//下载或者重新下载
//注意:这里的请求需要改成可变请求,因为后面要设置请求的下载位置
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://w.x.baidu.com/alading/anquan_soft_down_all/14247"]];
//需要一个全局的request以方便我暂停之后重新下载的时候设置下载的位置
self.request = request;
//设置请求头,从当前位置下载
NSString *range = [NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
[request setValue:range forHTTPHeaderField:@"Range"];
//单线程下载(非断点下载)
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}else{//按钮未被选中,暂停下载
//NSURLConnection不支持暂停,只能取消,重新开始任务时候从当前位置下载等同于取消操作
[self.connection cancel];
self.connection = nil;
}
}
//如果请求失败调用
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"didFailWithError---%@",error);
}
//建立连接获得相应的时候调用,只会调用一次,这里因为要实现断点续传,所以这个方法会调用多次,每次暂停一次就会重新调用一次
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse--接收到响应,开始下载--%@",response);
//下面这句非常重要,如果没有这一句,会重新创建新的文件,会出问题
if (self.currentLength) return;
NSString *filePath = @"/users/feng/desktop/QQ影音.exe";
NSFileManager *manager = [NSFileManager defaultManager];
[manager createFileAtPath:filePath contents:nil attributes:nil];
//建立句柄以方便后面每接受到一段数据可以插入到文件后面
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
self.handle = handle;
//统计该数据的总大小
self.totalLength = response.expectedContentLength;
}
//每次获取一段数据调用过一次,会调用多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// NSLog(@"didReceiveData----%@",data);
NSLog(@"didReceiveData------");
[self.handle seekToEndOfFile];
[self.handle writeData:data];
self.currentLength += data.length;
self.progressView.progress = (double)self.currentLength/self.totalLength;
}
//完成下载的时候调用一次
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"connectionDidFinishLoading");
[self.handle closeFile];
self.handle = nil;
self.totalLength = 0;
self.currentLength = 0;
self.btn.selected = NO;
}