文件下载

初始化下载管理器

1、遍历正下载Plist的所有字典成模型数组

2、给所有下载模型赋值Task

3、计算所有模型的已下载大小

4、将模型数组赋值给下载管理器的临时数组

添加下载

1、判断当前url文件的下载状态(已下载、正下载、未下载)

2、

下载数据管理

1、临时下载信息路径
/Library/Caches/DownLoad/CacheList/自行车.mp4.plist

2、下载完成文件路径
/Library/Caches/DownLoad/LocalList/自行车.mp4

3、FinishedPlist.plist
[self.filelist addObject:_fileInfo];

4、临时.plist文件Path->下载信息Model

5、计算已下载文件的大小,方便继续断点下载

创建请求

  • Get
//   NSURL
NSURL *url = [NSURL URLWithString:@""];
//   NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//   NSURLSession
NSURLSession *session = [NSURLSession sessionWithConfiguartion:[NSURLSessionConfiguration defaultSessionConfiguration]  delegate:self  delegateQueue:[[NSOpertationQueue alloc] init]];
//   NSURLSessionDataTask
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
     NSLog(@"%@", [NSJSONSerialazation JSONObjectWithData:data options:kNilOptions error:nil]);
}];
[task resume];
  • Post

  • Delegate
#pragma mark --------------------------------------- <NSURLSessionDataDelegate>
/**
 *  服务器开始响应
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // url标识符->请求模型
    JHDownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    // 请求模型->准备开始
    [info didReceiveResponse:response];
    
    // 更新本地Plist表
    [self addToLocalPlist:info];
    
    // 回调开始下载
    if([self.downloadDelegate respondsToSelector:@selector(startDownload:)]) {
        [self.downloadDelegate startDownload:info];
    }
    
    // 继续
    completionHandler(NSURLSessionResponseAllow);
}


/**
 *  服务器发送数据
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    JHDownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    [info didReceiveData:data];
    
    // 回调更新UI
    if([self.downloadDelegate respondsToSelector:@selector(updateCellProgress:)]) {
        [self.downloadDelegate updateCellProgress:info];
    }
}


/**
 *  服务器结束响应
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    JHDownloadInfo *info = [self downloadInfoForURL:task.taskDescription];
    
    [info didCompleteWithError:error];
    
    [self resumeFirstWillResume];
    
    // 更新本地Plist表
    [self addToLocalPlist:info];
    
    // 回调下载完成
    if([self.downloadDelegate respondsToSelector:@selector(finishedDownload:)]) {
        [self.downloadDelegate finishedDownload:info];
    }
}

下载数据本地化

/**
 *  获取已下载文件
 */
-(NSArray*)getDownloadedFile
{
    NSString *downloadedPlistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadedInfo.plist"] prependCaches];
    
    NSArray *downloadedDictArray  = [NSArray arrayWithContentsOfFile:downloadedPlistPath];
    
    NSArray *downloadedModelArray = [JHDownloadInfo mj_objectArrayWithKeyValuesArray:downloadedDictArray];
   
    
    return downloadedModelArray;
}


/**
 *  获取正下载文件
 */
-(NSArray*)getDownloadingFile
{
    NSString *downloadingPlistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadingInfo.plist"] prependCaches];
    
    NSArray *downloadingDictArray  = [NSArray arrayWithContentsOfFile:downloadingPlistPath];
    
    NSArray *downloadingModelArray = [JHDownloadInfo mj_objectArrayWithKeyValuesArray:downloadingDictArray];
    
    
    return downloadingModelArray;
}

/**
 *  删除某一个文件
 */
-(void)delete:(JHDownloadInfo*)info{
    // 修改Plist
    [self deleteLocalPlist:info];
    
    // 删除文件
    if ([[NSFileManager defaultManager] fileExistsAtPath:info.file]) {
        [[NSFileManager defaultManager] removeItemAtPath:info.file error:nil];
    }
}

/**
 *  修改本地Plist
 */
- (void)deleteLocalPlist:(JHDownloadInfo*)fileinfo{
    NSString *plistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadingInfo.plist"] prependCaches];
    if (fileinfo.state == JHDownloadStateCompleted){
        plistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadedInfo.plist"] prependCaches];
    }
        
        
    NSMutableArray *downloadingArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
    [downloadingArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *url = [dict objectForKey:@"url"];
        if ([url isEqualToString:fileinfo.url]) [downloadingArray removeObject:dict];
    }];
    [downloadingArray writeToFile:plistPath atomically:YES];
}


/**
 *  添加本地Plist
 */
- (void)addToLocalPlist:(JHDownloadInfo*)fileinfo
{
    NSDictionary *fileDic = [fileinfo mj_keyValuesWithKeys:@[@"state",@"bytesWritten",@"totalBytesWritten",@"totalBytesExpectedToWrite",@"filename",@"file",@"url"]];
    
    
    NSString *plistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadingInfo.plist"] prependCaches];
    if (fileinfo.state == JHDownloadStateCompleted){
        // 移除正下载
        NSMutableArray *downloadingArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        [downloadingArray enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *url = [dict objectForKey:@"url"];
            if ([url isEqualToString:fileinfo.url]) [downloadingArray removeObject:dict];
        }];
        [downloadingArray writeToFile:plistPath atomically:YES];
        
        // 添加新路径
        plistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadedInfo.plist"] prependCaches];
    }
    
    
    
    if([[NSFileManager defaultManager] fileExistsAtPath:plistPath]){
        NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
        [array addObject:fileDic];
        BOOL success = [array writeToFile:plistPath atomically:YES];
        NSLog(@"%@",success?@"写入成功":@"写入失败");
    }else{
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [array addObject:fileDic];
        BOOL success = [array writeToFile:plistPath atomically:YES];
        NSLog(@"%@",success?@"写入成功":@"写入失败");
    }
}

创建任务

  • NSURLSession:NSURLSessionConfiguration、NSOperationQueue

- (NSURLSession *)session
{
    if (!_session) {
        // 配置
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        // session
        self.session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:self.queue];
    }
    return _session;
}

- (NSOperationQueue *)queue
{
    if (!_queue) {
        self.queue = [[NSOperationQueue alloc] init];
        self.queue.maxConcurrentOperationCount = 1;
    }
    return _queue;
}
  • NSURLSessionDataDelegate

1、开始响应

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 获得下载信息
    DownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    // 处理响应
    [info didReceiveResponse:response];
    
    // 继续
    completionHandler(NSURLSessionResponseAllow);
}

2、正在响应

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    // 获得下载信息
    DownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    // 处理数据
    [info didReceiveData:data];
}

3、结束响应

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // 获得下载信息
    DownloadInfo *info = [self downloadInfoForURL:task.taskDescription];
    
    // 处理结束
    [info didCompleteWithError:error];
    
    // 恢复等待下载的
    [self resumeFirstWillResume];
}

开始任务

  • 获取下载模型

DownloadInfo *info = [self downloadInfoForURL:url];

#pragma mark - 获得下载信息
- (DownloadInfo *)downloadInfoForURL:(NSString *)url
{
    if (url == nil) return nil;
    
    DownloadInfo *info = [self.downloadInfoArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"url==%@", url]].firstObject;
    if (info == nil) {
        info = [[DownloadInfo alloc] init];
        info.url = url; // 设置url
        [self.downloadInfoArray addObject:info];
    }
    return info;
}
  • 最大并发数Vs当前正下载

NSArray *downloadingDownloadInfoArray = [self.downloadInfoArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"state==%d", MJDownloadStateResumed]];
if (self.maxDownloadingCount && downloadingDownloadInfoArray.count == self.maxDownloadingCount) {
        // 等待下载
        [info willResume];
    } else {
        // 开始下载
        [info resume];
    }
  • 等待下载

/** 任务 */
@property (strong, nonatomic) NSURLSessionDataTask *task;
  • 开始下载

/** 任务 */
@property (strong, nonatomic) NSURLSessionDataTask *task;

[self.task resume];

初始化下载管理器

  • 下载完成

/**
 *  服务器结束响应
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    JHDownloadInfo *info = [self downloadInfoForURL:task.taskDescription];
    
    [info didCompleteWithError:error];
    
    [self resumeFirstWillResume];
    
    if (!error) [self saveDownloadFile:info];
}

/**
 *  存储已下载文件
 */
- (void)saveDownloadFile:(JHDownloadInfo*)fileinfo
{
    NSString *downloadedPlistPath = [[NSString stringWithFormat:@"%@/%@", JHDownloadRootDir, @"DownloadedInfo.plist"] prependCaches];

    NSDictionary *fileDic = [fileinfo mj_keyValues];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:downloadedPlistPath]){
        NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:downloadedPlistPath];
        [array addObject:fileDic];
        BOOL success = [array writeToFile:downloadedPlistPath atomically:YES];
        NSLog(@"%@",success?@"写入成功":@"写入失败");
    }else{
        NSMutableArray *array = [[NSMutableArray alloc] init];
        [array addObject:fileDic];
        BOOL success = [array writeToFile:downloadedPlistPath atomically:YES];
        NSLog(@"%@",success?@"写入成功":@"写入失败");
    }
}

/**
 *  删除已下载的文件
 */
- (void)deleteFinishFile:(ZFFileModel *)selectFile
{
    [_finishedlist removeObject:selectFile];
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *path = FILE_PATH(selectFile.fileName);
    if ([fm fileExistsAtPath:path]) {
        [fm removeItemAtPath:path error:nil];
    }
    [self saveFinishedFile];
}

  • 下载中

/**
 * 下载文件所有信息存储为plist
 */
- (void)saveDownloadFile:(ZFFileModel*)fileinfo
{
    NSData *imagedata = UIImagePNGRepresentation(fileinfo.fileimage);
    NSDictionary *filedic = [NSDictionary dictionaryWithObjectsAndKeys:fileinfo.fileName,@"filename",
                             fileinfo.fileURL,@"fileurl",
                             fileinfo.time,@"time",
                             fileinfo.fileSize,@"filesize",
                             fileinfo.fileReceivedSize,@"filerecievesize",
                             imagedata,@"fileimage",nil];
    
    NSString *plistPath = [fileinfo.tempPath stringByAppendingPathExtension:@"plist"];
    if (![filedic writeToFile:plistPath atomically:YES]) {
        NSLog(@"write plist fail");
    }
}

/*
 *  将本地的未下载完成的临时文件加载到正在下载列表里,但是不接着开始下载
 */
- (void)loadTempfiles
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *filelist = [fileManager contentsOfDirectoryAtPath:TEMP_FOLDER error:&error];
    if(!error)
    {
        NSLog(@"%@",[error description]);
    }
    NSMutableArray *filearr = [[NSMutableArray alloc]init];
    for(NSString *file in filelist) {
        NSString *filetype = [file  pathExtension];
        if([filetype isEqualToString:@"plist"])
            [filearr addObject:[self getTempfile:TEMP_PATH(file)]];
    }
    
    NSArray* arr =  [self sortbyTime:(NSArray *)filearr];
    [_filelist addObjectsFromArray:arr];
    
    [self startLoad];
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容