NSURLSessionDataTask与NSOperation

2018-09-02  本文已影响178人  MasonCoder

效果展示

gif有点大,直接链接:http://7qnbrb.com1.z0.glb.clouddn.com/download.gif

知识要点

  1. NSOperationQueue线程队列的管理
  2. NSURLSession网络操作
  3. FMDB数据库操作

NSOperationQueue

NSURLSession

NSURLSession是iOS7中用于替换NSURLConnection而新增的接口,用于网络相关的操 作,包括数据请求,上传,下载,处理认证等工具,能处理http协议中的所用事情。但NSURLSession并不直接工作,而是由NSURLSessionTask完成,NSURLSessionTask 有三个子类:数据请求NSURLSessionDataTask,上传NSURLSessionUploadTask,下载NSURLSessionDownloadTask,可以使用block,delegate来进行初始化,当然使用NSURLSessionDataTask来进行上传和下载工作也是可行的。
关系结构

image

NSURLSessionDataTask与NSURLSessionDownloadTask方案选择的考虑

FMDB

关于FMDB,不做更多的介绍。

思路

添加下载任务到队列中

这里分两块:第一次新增,以及由暂停或失败状态重启

- (void)addDownloadQueue:(NSString *)fileUrl {
    MHDownloadModel *downloadModel = [self fetchDownloadModelWithFileUrl:fileUrl];
    if (downloadModel) {
        return;
    }
    //如果数据库中存在该文件,则表明仅仅只是由暂停或失败状态,重启下载(暂停 -> 正在下载)
    downloadModel = [[MHFileDatabase shareInstance] queryModelWitFileName:fileUrl.lastPathComponent];
    if (downloadModel) {
        //更新下载文件的状态
        [[MHFileDatabase shareInstance] updateDownloadStatusWithFileName:fileUrl.lastPathComponent downloadStatus:MHDownloadStatusDownloading];
    } else {
        //插入数据,记录下载文件
        [[MHFileDatabase shareInstance] insertFileWithFileName:fileUrl.lastPathComponent filePath:fileUrl fileTotalSize:0];
        downloadModel = [MHDownloadModel new];
        downloadModel.filePath = fileUrl;
    }
    [self.downloadTasks addObject:downloadModel];
    [self startDownLoadWithUrl:fileUrl];
}

启动下载任务

此时并不一定马上下载,下载的启动由NSOperationQueue控制,默认最大的下载并发数为3。

- (void)startDownLoadWithUrl:(NSString *)url {
    MHDownloadModel *downloadModel = [self fetchDownloadModelWithFileUrl:url];
    downloadModel.downloadStatus = MHDownloadStatusDownloadWait;
    NSURLSessionDataTask *task = downloadModel.task;
    if (task && task.state == NSURLSessionTaskStateRunning) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    MHURLSessionTaskOperation *operation = [MHURLSessionTaskOperation operationWithURLSessionTask:nil sessionBlock:^NSURLSessionTask *{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        NSLog(@"thread : %@, MHCustomOperation operationWithURLSessionTask", [NSThread currentThread]);
        return [strongSelf downloadDataTaskWithUrl:url];
    }];
    [self.operationQueue addOperation:operation];
}

封装下载请求:

1.设置url
2.设置request,设置请求头、请求体
3.发送请求

- (NSURLSessionDataTask *)downloadDataTaskWithUrl:(NSString *)url{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSDictionary *dic = [[NSFileManager defaultManager] attributesOfItemAtPath:[self getFilePathWithUrl:url] error:nil];
    MHDownloadModel *downloadModel = [self fetchDownloadModelWithFileUrl:url];
    downloadModel.currentSize = [dic[@"NSFileSize"] integerValue];
    [request setValue:[NSString stringWithFormat:@"bytes=%zd-",downloadModel.currentSize] forHTTPHeaderField:@"Range"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
    NSLog(@"thread : %@, 执行下载 --- %s", [NSThread currentThread], __func__);
    downloadModel.task = dataTask;
    return dataTask;
}

实现代理NSURLSessionDataDelegate

  • 开始下载:获取目标 文件的大小,创建沙盒文件
    必须调用 completionHandler (NSURLSessionResponseAllow)
- (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler
  • 获取下载进度,并将二进制数据写入沙盒
 - (void)URLSession:(NSURLSession *)session
          dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data
  • 下载完成或出错
- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error

完整案例:Github

上一篇 下一篇

猜你喜欢

热点阅读