1.采用 AFURLSessionManager 作为管理类
2.调用 NSURLSessionDownloadTask 类中的方法,做为下载类
- (NSURLSessionDownloadTask *)downloadTaskWithRequest:(NSURLRequest *)request progress:(NSProgress * __autoreleasing *)progress destination:(NSURL * (^)(NSURL *targetPath, NSURLResponse *response))destination completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
3. NSURLSessionDownloadTask方法中
[downloadTask resume]; //进行开始下载
[downloadTask suspend]; //进行暂停下载
4.调用 NSURLSessionTaskState state;方法判断状态
typedef NS_ENUM(NSInteger, NSURLSessionTaskState) { NSURLSessionTaskStateRunning = 0, /* 任务是否正在运行 */ NSURLSessionTaskStateSuspended = 1, //是否停止 NSURLSessionTaskStateCanceling = 2, /* 是否取消*/ NSURLSessionTaskStateCompleted = 3, /* 是否完成*/ }
示例:
- (Coding_DownloadTask *)addDownloadTaskForFile:(ProjectFile *)file completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler{ __weak typeof(file) weakFile = file; NSProgress *progress; NSURL *downloadURL = [NSURL URLWithString:file.downloadPath]; NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL]; NSURLSessionDownloadTask *downloadTask = [self.af_manager downloadTaskWithRequest:request progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) { NSURL *downloadUrl = [[Coding_FileManager sharedManager] urlForDownloadFolder]; Coding_DownloadTask *cDownloadTask = [[Coding_FileManager sharedManager] cDownloadTaskForResponse:response]; if (cDownloadTask) { downloadUrl = [downloadUrl URLByAppendingPathComponent:cDownloadTask.diskFileName]; }else{ downloadUrl = [downloadUrl URLByAppendingPathComponent:[response suggestedFilename]]; } NSLog(@"download_destinationPath------\n%@", downloadUrl.absoluteString); return downloadUrl; } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) { if (error) { [[Coding_FileManager sharedManager] removeCDownloadTaskForKey:weakFile.storage_key]; }else{ [[Coding_FileManager sharedManager] removeCDownloadTaskForResponse:response]; } if (completionHandler) { completionHandler(response, filePath, error); } }]; Coding_DownloadTask *cDownloadTask = [Coding_DownloadTask cDownloadTaskWithTask:downloadTask progress:progress fileName:file.diskFileName]; [self.downloadDict setObject:cDownloadTask forKey:file.storage_key]; [downloadTask resume]; return cDownloadTask; }
浙公网安备 33010602011771号