设计多线程下载器(利用HMFileMultiDownloader能开启多个线程同时下载一个文件)
一个多线程下载器只下载一个文件
YYFileMultiDownloader.h文件
#import "YYFileDownloader.h"
@interface YYFileMultiDownloader : YYFileDownloader
@end
YYFileMultiDownloader.m文件
#import "YYFileMultiDownloader.h"
#import "YYFileSingleDownloader.h"
#define YYMaxDownloadCount 4
@interface YYFileMultiDownloader()
@property (nonatomic, strong) NSMutableArray *singleDownloaders;
@property (nonatomic, assign) long long totalLength;
@end
@implementation YYFileMultiDownloader
- (void)getFilesize
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.url]];
request.HTTPMethod = @"HEAD";
NSURLResponse *response = nil;
#warning 这里要用异步请求
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
self.totalLength = response.expectedContentLength;
}
- (NSMutableArray *)singleDownloaders
{
if (!_singleDownloaders) {
_singleDownloaders = [NSMutableArray array];
// 获得文件大小
[self getFilesize];
// 每条路径的下载量
long long size = 0;
if (self.totalLength % YYMaxDownloadCount == 0) {
size = self.totalLength / YYMaxDownloadCount;
} else {
size = self.totalLength / YYMaxDownloadCount + 1;
}
// 创建N个下载器
for (int i = 0; i<YYMaxDownloadCount; i++) {
YYFileSingleDownloader *singleDownloader = [[YYFileSingleDownloader alloc] init];
singleDownloader.url = self.url;
singleDownloader.destPath = self.destPath;
singleDownloader.begin = i * size;
singleDownloader.end = singleDownloader.begin + size - 1;
singleDownloader.progressHandler = ^(double progress){
NSLog(@"%d --- %f", i, progress);
};
[_singleDownloaders addObject:singleDownloader];
}
// 创建一个跟服务器文件等大小的临时文件
[[NSFileManager defaultManager] createFileAtPath:self.destPath contents:nil attributes:nil];
// 让self.destPath文件的长度是self.totalLengt
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:self.destPath];
[handle truncateFileAtOffset:self.totalLength];
}
return _singleDownloaders;
}
/**
* 开始(恢复)下载
*/
- (void)start
{
[self.singleDownloaders makeObjectsPerformSelector:@selector(start)];
_downloading = YES;
}
/**
* 暂停下载
*/
- (void)pause
{
[self.singleDownloaders makeObjectsPerformSelector:@selector(pause)];
_downloading = NO;
}
@end
补充说明:如何获得将要下载的文件的大小?
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。










