NSURLConnection下载文件(断点下载)

1.小文件的下载

由于文件较小,我们可以直接可以使用NSURLConnection的异步请求(默认在这里开了一条线程,不回阻塞主线程)方法,在block里面进行数据接收:

[NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                               if (!connectionError) {
                                   dispatch_async(dispatch_get_main_queue(), ^{
                                       _imageView.image = [[UIImage alloc] initWithData:data];
                                   });
                               } else {
                                   NSLog(@"erorr = %@",[connectionError description]);
                               }
                           }];

可是大文件下载我们一般就不采用这种方式了,这种方式下载文件看不到进度,并且虽然在这里开了子线程来进行下载,可是在主线程的UI刷新是要等到服务器返回了总的文件data才会进行,这就给用户体验曹成了不好的地方,而且在大的文件下载过程中有可能会涉及到断点下载的情况(比如断网或者手动暂停)。

2.大文件的下载

具体思路是初始化一个NSMutableData类型的_responseData,在下载的过程中在- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data代理方法里面进行数据拼接,每次接收到数据就append,在代理方法- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {里面进行文件的写入,至于进度监听,可以在每次接收到数据的时候算目前接受到的总长度_currentDownLoadLength,然后除以文件的response.expectedContentLength,断点下载的关键是设置当前请求的请求头:

//设置请求头
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-",_currentDownLoadLength];
        [request setValue:range forHTTPHeaderField:@"Range"];

这里有一个新的东西:http协议请求头里面的Range,Range是请求头里面的下载起点(或者说下载的进度范围 ):

//Range 可以指定每次从网络下载数据包的大小
bytes = 0 - 499                   //从0到499共500
bytes = 500 -                    //从500到结束
bytes = -500                    //最后500
bytes = 500 - 599, 800 - 899    //同时指定几个范围

我们可以在暂停或者断网的情况下,记录当前的下载总长度,然后设置新的请求头,并重新初始化一个NSURLConnection对象,并在代理方法里面继续进行数据接收。
具体实现代理如下:

#pragma mark --NSURLConnectionDataDelegate
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:_fileName];
    //下载完成 写入文件
    [_responseData writeToFile:dbPath atomically:YES];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    _fileName = response.suggestedFilename;
    _totalLength = response.expectedContentLength;
    NSLog(@"fileName  = %@",response.suggestedFilename);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    //拼接每次接受的数据
    [_responseData appendData:data];
    //计算目前接收到的数据总长度
    _currentDownLoadLength = _currentDownLoadLength + data.length;
    //下载进度百分比
    NSString *subStr = @"%";
    NSLog(@"进度 = %@%.2f",subStr,  100.0 *_currentDownLoadLength /_totalLength);
}

#pragma mark --private Method
- (void)buttonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    button.selected = !button.selected;
    //断点下载
    if (button.selected) {
        //设置请求头
        NSString *range = [NSString stringWithFormat:@"bytes=%lld-",_currentDownLoadLength];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://download.xmcdn.com/group18/M01/BC/91/wKgJKlfAEN6wZgwhANQvLrUQ3Pg146.aac"]];
        [request setValue:range forHTTPHeaderField:@"Range"];
        //重新请求
        _connection = [[NSURLConnection alloc] initWithRequest:request
                                         delegate:self];
        [_connection start];
    } else  {
        //暂停
        [_connection cancel];
        _connection = nil;
    }
}

下载完成之后将_repsonseData写入sandBox,效果如下:


NSURLConnection下载文件(断点下载)_第1张图片
NSURLConnection下载.png

那么问题又来了,有些童鞋可能会发现,加入一个文件很大的情况下,会出现内存暴涨的情况,从而使程序报memory warning的情况,这样的代码是不完整的,也是质量不高的,于是我们要解决内存暴涨的问题

3.解决大文件内存暴涨问题

思路:我们注意到_responseData存在于内存中,每次append的是时候,内存就逐渐暴涨,于是我们可以开多个子线程来下载同一个文件,并且在下载的过程中可以边下载边写入沙盒sandBox,这就需要在接收到服务器响应的时候,开多个connection对象来下载(平分区域设置请求头的下载范围),使用NSFileHandel文件句柄写入沙盒,在finishload代理方法里面进行文件的合并处理,具体实现代码如下:

#pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    if ([connection isEqual:_connection]) {
        //获取总长度
        _totalWriteDataLength = response.expectedContentLength;
        //取消
        [_connection cancel];
        NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
        //开4个connection同时进行下载
        for (int i = 0; i < 4; i++) {
            //4个文件
            NSString *filePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_%d", response.suggestedFilename, i]];
            //创建4个临时文件
            NSFileManager *fileManager = [NSFileManager defaultManager];
            [fileManager createFileAtPath:filePath contents:nil attributes:nil];
            //创建请求
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://download.xmcdn.com/group18/M01/BC/91/wKgJKlfAEN6wZgwhANQvLrUQ3Pg146.aac"]];
            //平分每个Connection的下载范围
            NSString *range = [NSString stringWithFormat:@"bytes=%lld-%lld", response.expectedContentLength/4*i, response.expectedContentLength/4*(i+1)];
            [request setValue:range forHTTPHeaderField:@"Range"];
            //创建多个请求
            NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
            //创建4个文件句柄
            NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
            [_pathArray addObject:filePath];
            [_connectionArray addObject:connection];
            [_fileHandleArry addObject:fileHandle];
        }
    }
}

在finishload代理方法里面进行文件合并处理:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    _finishedCount++;
    NSInteger index = [_connectionArray indexOfObject:connection];
    //获取句柄
    NSFileHandle *fileHandle = [_fileHandleArry objectAtIndex:index];
    [fileHandle closeFile];
    fileHandle = nil;
    if (_finishedCount == 4)//将4个任务下载的文件合并成一个
    {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *tmpPath = [_pathArray objectAtIndex:index];
        NSString *filePath = [tmpPath substringToIndex:tmpPath.length];
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        //创建一个文件句柄
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
        for (int i = 0; i < 4; i++) {
            [fileHandle seekToEndOfFile];
            //向总文件写入数据
            [fileHandle writeData:[NSData dataWithContentsOfFile:[_pathArray objectAtIndex:i]]];
        }
        [fileHandle closeFile];
        fileHandle = nil;
    }
}

我们可以看内存不会存在暴涨的情况了,说明了这一些代码是有意义的,目前关于NSURLConnection的下载介绍就是这些,由于本人技术有限,写的不好的地方请大家指正,如果觉得本人对于您有帮助的话,请动用您宝贵的双手点个赞,谢谢!
作者------mrChan1234

你可能感兴趣的:(NSURLConnection下载文件(断点下载))