需求:1、下载大文件
2、取消下载,和暂停下载,继续下载
3、显示下载进度
1、第一种方式基于:NSURLConnection(备注:该方法在iOS9已经被弃用了)
a、首先声明需要用得变量
@property (nonatomic,strong) NSFileHandle *fileHandle; // 文件句柄
@property (nonatomic,assign) long long totalFileLength; // 记录下载
@property (nonatomic,assign) long long currentFileLength; // 已经下载好的长度
@property (nonatomic,strong) NSURLConnection *connection;
b、在下载按钮中实现下载和取消下载(记得遵守NSURLConnectionDataDelegate协议)
- (IBAction)downAction:(UIButton *)sender {
sender.selected = !sender.selected;
if (sender.selected) {
//下载
NSString *urlString = @"youdwonloadpath"; // 下载路径
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//设置请求头下载范围从哪里开始(很重要)
NSString *range = [NSString stringWithFormat:@"bytes=%lld",self.currentFileLength];
[request setValue:range forHTTPHeaderField:@"Range"];
// 发起异步下载请求
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
else {
//取消下载
[self.connection cancel];
}
}
c、NSURLConnectionDataDelegate方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if (self.currentFileLength) {
return;
} // 如果已经下载了,就不要再创建文件夹了
// 开始响应
//1、首先获取文件的长度
self.totalFileLength = response.expectedContentLength;
// 创建一个空的文件
NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"video.zip"];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createFileAtPath:filePath contents:nil attributes:nil];
// 创建一个文件句柄
self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// 接受数据
self.currentFileLength+=data.length;
float progress = (double)self.currentFileLength/self.totalFileLength;
NSLog(@"%f",progress);
//文件最后面
[self.fileHandle seekToEndOfFile];
// 把数据拼接到文件最后面
[self.fileHandle writeData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// 下载完成
self.currentFileLength = 0;
self.totalFileLength = 0;
// 一定要关闭
[self.fileHandle closeFile];
self.fileHandle = nil;
}
2、第二种方式基于:NSURLSession的大文件下载(备注:该方法iOS7才推出,苹果推荐)
a、遵守协议NSURLSessionDownloadDelegate,NSURLSessionDataDelegate
申明变量
/**
* 下载任务
*/
@property(nonatomic, strong) NSURLSessionDownloadTask *downLoadTask;
@property(nonatomic, strong) NSURLSession *session;
@property(nonatomic, strong) NSData *resumeData; // 暂停下载返回的数据
b、下载按钮中实现
- (IBAction)downLoadAction:(UIButton *)sender {
sender.selected = !sender.selected;
if (sender.selected) {
if (self.resumeData) {
[self resumeDownLoad];
}
else {
[self startDownLoad];
}
}
else {
[self pauseDownLoad];
}
}
几个方法的实现
// 开始下载
- (void)startDownLoad {
NSString *urlString = @"youdownloadpath"; // 下载路径
// 创建下载任务
self.downLoadTask = [self.session downloadTaskWithURL:[NSURL URLWithString:urlString]];
// 开始下载任务
[self.downLoadTask resume];
}
// 恢复下载
- (void)resumeDownLoad {
// 传入上次暂停下载返回的数据,就可以恢复下载
self.downLoadTask = [self.session downloadTaskWithResumeData:self.resumeData];
[self.downLoadTask resume];
// 记得请空resumeData
self.resumeData = nil;
}
// 暂停下载
- (void)pauseDownLoad {
//取消任务
__weak typeof(self) weakSelf = self;
[self.downLoadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
weakSelf.resumeData = resumeData;
//记得清空任务
weakSelf.downLoadTask = nil;
}];
}
c、代理方法中的实现(重要)
// 恢复下载时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
// 在这里显示进度条
self.progressView.progress = (double)totalBytesWritten/totalBytesExpectedToWrite;
}
// 下载完成后调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [cachesPath stringByAppendingString:downloadTask.response.suggestedFilename];
//剪切文件到指定的路径
NSFileManager *manager = [NSFileManager defaultManager];
[manager moveItemAtPath:location.path toPath:filePath error:nil];
}
总结:
个人认为NSURLSession使用简单一点,不用设置请求头啊,也不要自己拼接数据存储,毕竟苹果推荐
网友评论