一、整体框架及思路
主要涉及两个类,
1、DownloadManager,文件下载管理器是一个单例,负责调度和管理具体的下载操作。它主要有两个属性,下载操作缓存(字典类型),以url为key,防止相同的下载操作多次执行。下载队列(NSOperationQueue),用来控制并发数,防止队列中同时有过多的下载操作同时执行。
2、DownloadOperation,文件下载操作,对应具体的下载操作,继承于NSOperation。相关注意点:1、执行下载请求前,先同步发送一个HEAD请求,获取目标文件的大小,经过和本地文件比对后确定断点下载的断点。 2、通过设置range请求头告诉服务器断点,这是断点下载的核心。3、在循环接收服务器返回的文件数据过程中,如果用全局属性去拼接,会造成内存浪费。可以用NSOutputStream解决内存峰值问题,每接收一点,就写到本地文件中。
外界调动示例:
//要下载的文件的URL
NSURL *url = [NSURL URLWithString:@"http://dlsw.baidu.com/sw-search-sp/soft/2a/25677/QQ_V4.1.1.1456905733.dmg"];
//通过下载管理器单例执行下载
[[downloadManager sharedManager] downloadWith:url pregressBlock:^(CGFloat progress) {
//进度回调,返回下载进度
dispatch_async(dispatch_get_main_queue(), ^{
//回到主线程刷新进度提醒
self.progress.progress = progress;
});
} complete:^(NSString *path, NSError *error) {
//完成回调,返回文件路径或者失败信息
NSLog(@"下载完成%@",path);
}];
二
实现代码:
DownloadManager.m
@interface downloadManager()
/**
* 下载操作缓存,以url为key,防止多次下载
*/
@property (nonatomic,strong)NSMutableDictionary *downloadCache;
/**
* 下载队列,可以控制并发数
*/
@property (nonatomic,strong)NSOperationQueue *downloadQueue;
@end
@implementation downloadManager
/**
* 下载管理器单例
*
* @return 返回唯一的实例
*/
+ (instancetype)sharedManager{
static dispatch_once_t onceToken;
static downloadManager *manager;
dispatch_once(&onceToken, ^{
manager = [[self alloc]init];
});
return manager;
}
/**
* 下载操作
*
* @param url 要下载的url
* @param progressBlock 进度回调
* @param complete 完成回调
*/
- (void)downloadWith:(NSURL *)url pregressBlock:(void (^)(CGFloat progress))progressBlock complete:(void(^)(NSString *path,NSError *error))complete{
//在开始下载之前,判断是否正在下载
if ([self.downloadCache objectForKey:url]) {
NSLog(@"正在下载");
return;
}
//开始下载文件
downloadOperation *download = [downloadOperation downloadWith:url progressBlock:progressBlock complete:^(NSString *path, NSError *error) {
//下载完成
//移除下载操作缓存
[self.downloadCache removeObjectForKey:url];
//调用控制器传过来的完成回调
complete(path,error);
}];
//把下载操作保存起来
[self.downloadCache setObject:download forKey:url];
//把操作发到队列中
[self.downloadQueue addOperation:download];
}
- (void)cancelDownload:(NSURL *)url{
//从字典中取出下载操作
downloadOperation *down = [self.downloadCache objectForKey:url];
[down cancleDown];
//从字典中移除
[self.downloadCache removeObjectForKey:url];
}
#pragma mark -数据懒加载
- (NSMutableDictionary *)downloadCache{
if (_downloadCache == nil) {
_downloadCache = [NSMutableDictionary dictionary];
}
return _downloadCache;
}
- (NSOperationQueue *)downloadQueue{
if (_downloadQueue == nil) {
_downloadQueue = [[NSOperationQueue alloc]init];
//设置最大并发数
_downloadQueue.maxConcurrentOperationCount = 3;
}
return _downloadQueue;
}
@end
DownloadOperation.m
@interface downloadOperation()
/**
* 文件总大小
*/
@property (nonatomic,assign)long long expectLength;
/**
* 已经下载的大小
*/
@property (nonatomic,assign)long long downloadLength;
/**
* 文件输出流
*/
@property (nonatomic,strong)NSOutputStream *outPut;
/**
* 下载连接
*/
@property (nonatomic,strong)NSURLConnection *connection;
/**
* 进度回调block
*/
@property (nonatomic,copy)void (^progressBlock)(CGFloat);
/**
* 完成回调block
*/
@property (nonatomic,copy)void (^complete)(NSString *,NSError *);
/**
* 文件保存的路径
*/
@property (nonatomic,copy)NSString *targetPath;
/**
* <#Description#>
*/
@property (nonatomic,strong)NSURL *url;
@end
@implementation downloadOperation
+ (instancetype)downloadWith:(NSURL *)url progressBlock:(void (^)(CGFloat progress))progressBlock complete:(void (^)(NSString *path,NSError *error))complete{
downloadOperation *down = [[self alloc]init];
//把block保存起来
down.progressBlock = progressBlock;
down.complete = complete;
//拼接文件保存的路径
down.targetPath = [url.path appendCaches];
down.url = url;
//调用下载方法
//[down download:url];
return down;
}
- (void)main{
@autoreleasepool {
[self download];
}
}
- (void)download{
NSURL *url = self.url;
//断点下载,如果完全相同,不下载。否则,从fileSize开始下载
long long fileSize = [self checkServerFileSize:url];
if (fileSize == self.expectLength) {
return ;
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//断点续传必须设置range请求头
NSString *range = [NSString stringWithFormat:@"bytes=%lld-",fileSize];
//下载进度就是本地文件的大小
self.downloadLength = fileSize;
//设置请求头
[request setValue:range forHTTPHeaderField:@"range"];
//开始下载,通过遵守代理协议,回调下载过程
[NSURLConnection connectionWithRequest:request delegate:self];
//如果子线程在执行完当前代码后需要一直保持的,需要把runloop跑起来
[[NSRunLoop currentRunLoop] run];
}
//检查服务器上文件的大小
- (long long)checkServerFileSize:(NSURL *)url{
//要下载文件的url
//NSURL *url = [NSURL URLWithString:@"http://dlsw.baidu.com/sw-search-sp/soft/2a/25677/QQ_V4.1.1.1456905733.dmg"];
//创建获取文件大小的请求
NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
//请求方法
headRequest.HTTPMethod = @"HEAD";
//创建一个响应头
NSURLResponse *headResponse;
[NSURLConnection sendSynchronousRequest:headRequest returningResponse:&headResponse error:nil];
long long serverSize = headResponse.expectedContentLength;
//记录服务器文件的大小,用于计算进度
self.expectLength = serverSize;
//拼接文件路径
NSString *path = [headResponse.suggestedFilename appendCaches];
//判断服务器文件大小跟本地文件大小的关系
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
NSLog(@"不存在,从头开始下载");
return 0;
}
//获取文件的属性
NSDictionary *dict = [manager attributesOfItemAtPath:path error:nil];
//获取本地文件的大小
long long fileSize = dict.fileSize;
if (fileSize > serverSize) {
//文件出错,删除文件
[manager removeItemAtPath:path error:nil];
NSLog(@"从头开始");
return 0;
}else if(fileSize < serverSize){
NSLog(@"从本地文件大小开始下载");
return fileSize;
}else{
NSLog(@"已经下载完毕");
return fileSize;
}
}
#pragma mark -下载回调
//获得相应,响应头中包含了文件总大小的信息
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// //设置文件总大小
// self.expectLength = response.expectedContentLength;
NSString *path = self.targetPath;
//不需要手动去创建,如果文件不存在,自动创建
self.outPut = [NSOutputStream outputStreamToFileAtPath:path append:YES];
//在入文件之前,先打开文件
[self.outPut open];
}
//接收到数据
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//分多次接收数据,加起来就是总数据
self.downloadLength += data.length;
//计算当前下载进度
CGFloat progress = self.downloadLength *1.0 / self.expectLength;
//NSLog(@"当前进度%f",progress);
//进度回调调用的频率非常高,我们可以在子线程回调。用户是否要刷新UI,由自己决定
if (self.progressBlock) {
self.progressBlock(progress);
}
//保存每次接收到的数据
//#warning 每次的数据都保存在内存中,消耗大量内存
// [self.data appendData:data];
//解决方法:使用文件句柄
[self.outPut write:data.bytes maxLength:data.length];
}
//下载完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//关闭文件
[self.outPut close];
//下载完成后,自动回到主线程
dispatch_async(dispatch_get_global_queue(0, 0), ^{
self.complete(self.targetPath,nil);
});
}
//取消下载
- (void)cancleDown{
[self.connection cancel];
}
@end
其他
NSString+Path.m
@implementation NSString (Path)
- (NSString *)appendCaches {
// 获取缓存目录
NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 获取路径的最后一部份(文件名)
NSString *filename = [self lastPathComponent];
return [cache stringByAppendingPathComponent:filename];
}
- (NSString *)appendDocuments {
// 获取缓存目录
NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 获取路径的最后一部份(文件名)
NSString *filename = [self lastPathComponent];
return [document stringByAppendingPathComponent:filename];
}
- (NSString *)appendTmp {
// 获取缓存目录
NSString *temp = NSTemporaryDirectory();
// 获取路径的最后一部份(文件名)
NSString *filename = [self lastPathComponent];
return [temp stringByAppendingPathComponent:filename];
}
网友评论