文件下載

初始化下載管理器

1弛槐、遍歷正下載Plist的所有字典成模型數(shù)組

2章蚣、給所有下載模型賦值Task

3、計算所有模型的已下載大小

4摆马、將模型數(shù)組賦值給下載管理器的臨時數(shù)組

添加下載

1、判斷當(dāng)前url文件的下載狀態(tài)(已下載棕孙、正下載丸逸、未下載)

2、

下載數(shù)據(jù)管理

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、計算已下載文件的大小略板,方便繼續(xù)斷點下載

創(chuàng)建請求

  • 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>
/**
 *  服務(wù)器開始響應(yīng)
 */
- (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];
    
    // 回調(diào)開始下載
    if([self.downloadDelegate respondsToSelector:@selector(startDownload:)]) {
        [self.downloadDelegate startDownload:info];
    }
    
    // 繼續(xù)
    completionHandler(NSURLSessionResponseAllow);
}


/**
 *  服務(wù)器發(fā)送數(shù)據(jù)
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    JHDownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    [info didReceiveData:data];
    
    // 回調(diào)更新UI
    if([self.downloadDelegate respondsToSelector:@selector(updateCellProgress:)]) {
        [self.downloadDelegate updateCellProgress:info];
    }
}


/**
 *  服務(wù)器結(jié)束響應(yīng)
 */
- (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];
    
    // 回調(diào)下載完成
    if([self.downloadDelegate respondsToSelector:@selector(finishedDownload:)]) {
        [self.downloadDelegate finishedDownload:info];
    }
}

下載數(shù)據(jù)本地化

/**
 *  獲取已下載文件
 */
-(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?@"寫入成功":@"寫入失敗");
    }
}

創(chuàng)建任務(wù)

  • 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、開始響應(yīng)

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 獲得下載信息
    DownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    // 處理響應(yīng)
    [info didReceiveResponse:response];
    
    // 繼續(xù)
    completionHandler(NSURLSessionResponseAllow);
}

2叮称、正在響應(yīng)

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    // 獲得下載信息
    DownloadInfo *info = [self downloadInfoForURL:dataTask.taskDescription];
    
    // 處理數(shù)據(jù)
    [info didReceiveData:data];
}

3种玛、結(jié)束響應(yīng)

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // 獲得下載信息
    DownloadInfo *info = [self downloadInfoForURL:task.taskDescription];
    
    // 處理結(jié)束
    [info didCompleteWithError:error];
    
    // 恢復(fù)等待下載的
    [self resumeFirstWillResume];
}

開始任務(wù)

  • 獲取下載模型

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; // 設(shè)置url
        [self.downloadInfoArray addObject:info];
    }
    return info;
}
  • 最大并發(fā)數(shù)Vs當(dāng)前正下載

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

/** 任務(wù) */
@property (strong, nonatomic) NSURLSessionDataTask *task;
  • 開始下載

/** 任務(wù) */
@property (strong, nonatomic) NSURLSessionDataTask *task;

[self.task resume];

初始化下載管理器

  • 下載完成

/**
 *  服務(wù)器結(jié)束響應(yīng)
 */
- (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];
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市瓤檐,隨后出現(xiàn)的幾起案子赂韵,更是在濱河造成了極大的恐慌,老刑警劉巖挠蛉,帶你破解...
    沈念sama閱讀 212,542評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件祭示,死亡現(xiàn)場離奇詭異,居然都是意外死亡谴古,警方通過查閱死者的電腦和手機质涛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評論 3 385
  • 文/潘曉璐 我一進店門稠歉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人汇陆,你說我怎么就攤上這事怒炸。” “怎么了瞬测?”我有些...
    開封第一講書人閱讀 158,021評論 0 348
  • 文/不壞的土叔 我叫張陵横媚,是天一觀的道長纠炮。 經(jīng)常有香客問我月趟,道長,這世上最難降的妖魔是什么恢口? 我笑而不...
    開封第一講書人閱讀 56,682評論 1 284
  • 正文 為了忘掉前任孝宗,我火速辦了婚禮,結(jié)果婚禮上耕肩,老公的妹妹穿的比我還像新娘因妇。我一直安慰自己,他們只是感情好猿诸,可當(dāng)我...
    茶點故事閱讀 65,792評論 6 386
  • 文/花漫 我一把揭開白布婚被。 她就那樣靜靜地躺著,像睡著了一般梳虽。 火紅的嫁衣襯著肌膚如雪址芯。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,985評論 1 291
  • 那天窜觉,我揣著相機與錄音谷炸,去河邊找鬼。 笑死禀挫,一個胖子當(dāng)著我的面吹牛旬陡,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播语婴,決...
    沈念sama閱讀 39,107評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼描孟,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了砰左?” 一聲冷哼從身側(cè)響起匿醒,我...
    開封第一講書人閱讀 37,845評論 0 268
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎菜职,沒想到半個月后青抛,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,299評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡酬核,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,612評論 2 327
  • 正文 我和宋清朗相戀三年蜜另,在試婚紗的時候發(fā)現(xiàn)自己被綠了适室。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,747評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡举瑰,死狀恐怖捣辆,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情此迅,我是刑警寧澤汽畴,帶...
    沈念sama閱讀 34,441評論 4 333
  • 正文 年R本政府宣布,位于F島的核電站耸序,受9級特大地震影響忍些,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜坎怪,卻給世界環(huán)境...
    茶點故事閱讀 40,072評論 3 317
  • 文/蒙蒙 一罢坝、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧搅窿,春花似錦嘁酿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至沐飘,卻和暖如春游桩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背薪铜。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評論 1 267
  • 我被黑心中介騙來泰國打工众弓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人隔箍。 一個月前我還...
    沈念sama閱讀 46,545評論 2 362
  • 正文 我出身青樓谓娃,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蜒滩。 傳聞我的和親對象是個殘疾皇子滨达,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,658評論 2 350

推薦閱讀更多精彩內(nèi)容