版权声明:本文为博主原创文章,未经博主允许不得转载。 https://cloud.tencent.com/developer/article/1337687
在iOS开发中我们如果要下载一个大的文件可能会有断点下载的需求即能够对下载任务进行暂停,之后再开始下载任务,下面即将给出利用AFNetworking进行断点下载的代码。核心思想:将下载的文件的长度记录下载,然后再次下载的时候即发送网络请求的时候在请求头中设置下载数据的位置。关键代码:
// 设置HTTP请求头中的Range
NSString *range = NSString stringWithFormat:@"bytes=%zd-", self.currentLength;
request setValue:range forHTTPHeaderField:@"Range";
全部代码:
.m文件中的代码:
#import "AFNetworkingOfflineResumeDownloadFileViewController.h"
#import <AFNetworking.h>
@interface AFNetworkingOfflineResumeDownloadFileViewController ()
/** 下载进度条 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下载进度条Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
/** AFNetworking断点下载(支持离线)需用到的属性 **********/
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 当前下载长度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄对象 */
@property (nonatomic, strong) NSFileHandle *fileHandle;
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDataTask *downloadTask;
/* AFURLSessionManager */
@property (nonatomic, strong) AFURLSessionManager *manager;
@end
@implementation AFNetworkingOfflineResumeDownloadFileViewController
super viewDidLoad;
self.navigationItem.title = @"AFNetworking断点下载(支持离线)";
}
/**
* manager的懒加载
*/
if (!_manager) {
NSURLSessionConfiguration *configuration = NSURLSessionConfiguration defaultSessionConfiguration;
// 1. 创建会话管理者
_manager = [AFURLSessionManager alloc initWithSessionConfiguration:configuration];
}
return _manager;
}
/**
* downloadTask的懒加载
*/
if (!_downloadTask) {
// 创建下载URL
NSURL *url = NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg";
// 2.创建request请求
NSMutableURLRequest *request = NSMutableURLRequest requestWithURL:url;
// 设置HTTP请求头中的Range
NSString *range = NSString stringWithFormat:@"bytes=%zd-", self.currentLength;
request setValue:range forHTTPHeaderField:@"Range";
__weak typeof(self) weakSelf = self;
_downloadTask = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSLog(@"dataTaskWithRequest");
// 清空长度
weakSelf.currentLength = 0;
weakSelf.fileLength = 0;
// 关闭fileHandle
weakSelf.fileHandle closeFile;
weakSelf.fileHandle = nil;
}];
// 第一次收到服务器的响应的block
[self.manager setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSURLResponse * _Nonnull response) {
NSLog(@"NSURLSessionResponseDisposition");
if (weakSelf.currentLength){
return NSURLSessionResponseAllow;
}else{
// 获得下载文件的总长度:请求下载的文件长度 + 当前已经下载的文件长度
// weakSelf.fileLength = response.expectedContentLength + self.currentLength;
weakSelf.fileLength = response.expectedContentLength;
// 沙盒文件路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSLog(@"File downloaded to: %@",path);
// 创建一个空的文件到沙盒中
NSFileManager *manager = NSFileManager defaultManager;
if (undefined) {
// 如果没有下载文件的话,就创建一个文件。如果有下载文件的话,则不用重新创建(不然会覆盖掉之前的文件)
manager createFileAtPath:path contents:nil attributes:nil;
}
// 创建文件句柄
weakSelf.fileHandle = NSFileHandle fileHandleForWritingAtPath:path;
// 允许处理服务器的响应,才会继续接收服务器返回的数据
return NSURLSessionResponseAllow;
}
}];
// 收到服务器返回的数据的block
[self.manager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
NSLog(@"setDataTaskDidReceiveDataBlock");
// 指定数据的写入位置 -- 文件内容的最后面
weakSelf.fileHandle seekToEndOfFile;
// 向沙盒写入数据
weakSelf.fileHandle writeData:data;
// 拼接文件总长度
weakSelf.currentLength += data.length;
// 获取主线程,不然无法正确显示进度。
NSOperationQueue* mainQueue = NSOperationQueue mainQueue;
[mainQueue addOperationWithBlock:^{
// 下载进度
if (weakSelf.fileLength == 0) {
weakSelf.progressView.progress = 0.0;
weakSelf.progressLabel.text = NSString stringWithFormat:@"当前下载进度:00.00%%";
} else {
weakSelf.progressView.progress = 1.0 * weakSelf.currentLength / weakSelf.fileLength;
weakSelf.progressLabel.text = NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * weakSelf.currentLength / weakSelf.fileLength;
}
}];
}];
}
return _downloadTask;
}
/**
* 点击按钮 -- 使用AFNetworking断点下载(支持离线)
*/
// 按钮状态取反
sender.selected = !sender.isSelected;
if (sender.selected) { // 开始下载/继续下载
// 沙盒文件路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSInteger currentLength = self fileLengthForPath:path;
if (currentLength > 0) { // 继续下载
self.currentLength = currentLength;
}
self.downloadTask resume;
} else {
// 暂停下载
self.downloadTask suspend;
self.downloadTask = nil;
}
}
/**
* 获取已下载的文件大小
*/
NSInteger fileLength = 0;
NSFileManager *fileManager = [NSFileManager alloc init]; // default is not thread safe
if (fileManager fileExistsAtPath:path) {
NSError *error = nil;
NSDictionary *fileDict = fileManager attributesOfItemAtPath:path error:&error;
if (!error && fileDict) {
fileLength = fileDict fileSize;
}
}
return fileLength;
}
@end