AFNetworking下载文件
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 创建会话管理者
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
// 2. 创建下载路径和请求对象
NSURL *URL = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
// 3.创建下载任务
/**
* 第一个参数 - request:请求对象
* 第二个参数 - progress:下载进度block
* 其中: downloadProgress.completedUnitCount:已经完成的大小
* downloadProgress.totalUnitCount:文件的总大小
* 第三个参数 - destination:自动完成文件剪切操作
* 其中: 返回值:该文件应该被剪切到哪里
* targetPath:临时路径 tmp NSURL
* response:响应头
* 第四个参数 - completionHandler:下载完成回调
* 其中: filePath:真实路径 == 第三个参数的返回值
* error:错误信息
*/
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress) {
// 下载进度
self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
self.progressLabel.text = [NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSURL *path = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [path URLByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
NSLog(@"File downloaded to: %@", filePath);
}];
// 4. 开启下载任务
[downloadTask resume];
AFNetworking断点下载,离线下载
@interface ViewController ()
/** 下载进度条 */
@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
/**
* manager的懒加载
*/
- (AFURLSessionManager *)manager {
if (!_manager) {
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// 1. 创建会话管理者
_manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
}
return _manager;
}
/**
* downloadTask的懒加载
*/
- (NSURLSessionDataTask *)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;
}];
[self.manager setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSURLResponse * _Nonnull response) {
NSLog(@"NSURLSessionResponseDisposition");
// 获得下载文件的总长度:请求下载的文件长度 + 当前已经下载的文件长度
weakSelf.fileLength = response.expectedContentLength + self.currentLength;
// 沙盒文件路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSLog(@"File downloaded to: %@",path);
// 创建一个空的文件到沙盒中
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
// 如果没有下载文件的话,就创建一个文件。如果有下载文件的话,则不用重新创建(不然会覆盖掉之前的文件)
[manager createFileAtPath:path contents:nil attributes:nil];
}
// 创建文件句柄
weakSelf.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// 允许处理服务器的响应,才会继续接收服务器返回的数据
return NSURLSessionResponseAllow;
}];
[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断点下载(支持离线)
*/
- (IBAction)OfflinResumeDownloadBtnClicked:(UIButton *)sender {
// 按钮状态取反
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)fileLengthForPath:(NSString *)path {
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;
}
直接下载NSData
// 创建下载路径
NSURL *url = [NSURL URLWithString:@"http://pics.sc.chinaz.com/files/pic/pic9/201508/apic14052.jpg"];
// 使用NSData的dataWithContentsOfURL:方法下载
NSData *data = [NSData dataWithContentsOfURL:url];
// 如果下载的是将要显示的图片,则可以显示出来
// 如果下载的是其他文件,然后可以将data转存为本地文件
NSURLSession下载
如果想要监听下载进度,我们就需要用到NSURLSessionDownloadDelegate。
具体使用方式就是使用代理的方法创建下载任务,并且实现对应的代理方法。
// 创建下载路径
NSURL *url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
// 创建NSURLSession对象,并设计代理方法。其中NSURLSessionConfiguration为默认配置
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
// 创建任务
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
// 开始任务
[downloadTask resume];
#pragma mark <NSURLSessionDownloadDelegate> 实现方法
/**
* 文件下载完毕时调用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
// 文件将要移动到的指定目录
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
// 新文件路径
NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSLog(@"File downloaded to: %@",newFilePath);
// 移动文件到新路径
[[NSFileManager defaultManager] moveItemAtPath:location.path toPath:newFilePath error:nil];
}
/**
* 每次写入数据到临时文件时,就会调用一次这个方法。可在这里获得下载进度
*
* @param bytesWritten 这次写入的文件大小
* @param totalBytesWritten 已经写入沙盒的文件大小
* @param totalBytesExpectedToWrite 文件总大小
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
// 下载进度
self.progressView.progress = 1.0 * totalBytesWritten / totalBytesExpectedToWrite;
self.progressLabel.text = [NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * totalBytesWritten / totalBytesExpectedToWrite];
}
/**
* 恢复下载后调用
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
}
NSURLSession 断点下载,不支持离线
NSURLSession断点下载(不支持离线)实现断点下载的步骤如下:
在实现断点下载的[开始/暂停]按钮中添加以下步骤:
设置一个downloadTask、session以及resumeData的全局变量
如果开始下载,就创建一个新的downloadTask,并启动下载
如果暂停下载,调用取消下载的函数,并在block中保存本次的resumeData到全局resumeData中。
如果恢复下载,将上次保存的resumeData加入到任务中,并启动下载。
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下载进度条 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下载进度条Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
/** NSURLSession断点下载(不支持离线)需用到的属性 **********/
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
/** 保存上次的下载信息 */
@property (nonatomic, strong) NSData *resumeData;
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
/**
* 点击按钮 -- 使用NSURLSession断点下载(不支持离线)
*/
- (IBAction)resumeDownloadBtnClicked:(UIButton *)sender {
// 按钮状态取反
sender.selected = !sender.isSelected;
if (nil == self.downloadTask) { // [开始下载/继续下载]
if (self.resumeData) { // [继续下载]
// 传入上次暂停下载返回的数据,就可以恢复下载
self.downloadTask = [self.session downloadTaskWithResumeData:self.resumeData];
// 开始任务
[self.downloadTask resume];
self.resumeData = nil;
}else{ // [开始下载]:从0开始下载
NSURL* url = [NSURL URLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];
// 创建任务
self.downloadTask = [self.session downloadTaskWithURL:url];
// 开始任务
[self.downloadTask resume];
}
}else{ // [暂停下载]
__weak typeof(self) weakSelf = self;
[self.downloadTask cancelByProducingResumeData:^(NSData *resumeData) {
// resumeData:包含了继续下载的位置\下载的路径
weakSelf.resumeData = resumeData;
weakSelf.downloadTask = nil;
}];
}
}
NSURLSession(断点下载 | 支持离线)
@interface ViewController () <NSURLSessionDataDelegate>
/** 下载进度条 */
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 下载进度条Label */
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
/** NSURLSession断点下载(支持离线)需用到的属性 **********/
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger fileLength;
/** 当前下载长度 */
@property (nonatomic, assign) NSInteger currentLength;
/** 文件句柄对象 */
@property (nonatomic, strong) NSFileHandle *fileHandle;
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDataTask *downloadTask;
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end
/**
* session的懒加载
*/
- (NSURLSession *)session
{
if (!_session) {
_session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
}
/**
* downloadTask的懒加载,这里设置请求头中的Range
*/
- (NSURLSessionDataTask *)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"];
// 3. 下载
_downloadTask = [self.session dataTaskWithRequest:request];
}
return _downloadTask;
}
/**
* 点击按钮 -- 使用NSURLSession断点下载(支持离线)
*/
- (IBAction)OfflinResumeDownloadBtnClicked:(UIButton *)sender {
// 按钮状态取反
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)fileLengthForPath:(NSString *)path {
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;
}
#pragma mark - <NSURLSessionDataDelegate> 实现方法
/**
* 接收到响应的时候:创建一个空的沙盒文件
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 获得下载文件的总长度:请求下载的文件长度 + 当前已经下载的文件长度
self.fileLength = response.expectedContentLength + self.currentLength;
// 沙盒文件路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"QQ_V5.4.0.dmg"];
NSLog(@"File downloaded to: %@",path);
// 创建一个空的文件到沙盒中
NSFileManager *manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:path]) {
// 如果没有下载文件的话,就创建一个文件。如果有下载文件的话,则不用重新创建(不然会覆盖掉之前的文件)
[manager createFileAtPath:path contents:nil attributes:nil];
}
// 创建文件句柄
self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
// 允许处理服务器的响应,才会继续接收服务器返回的数据
completionHandler(NSURLSessionResponseAllow);
}
/**
* 接收到具体数据:把数据写入沙盒文件中
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
// 指定数据的写入位置 -- 文件内容的最后面
[self.fileHandle seekToEndOfFile];
// 向沙盒写入数据
[self.fileHandle writeData:data];
// 拼接文件总长度
self.currentLength += data.length;
NSLog(@"%ld",self.currentLength);
__weak typeof(self) weakSelf = self;
// 获取主线程,不然无法正确显示进度。
NSOperationQueue* mainQueue = [NSOperationQueue mainQueue];
[mainQueue addOperationWithBlock:^{
// 下载进度
weakSelf.progressView.progress = 1.0 * weakSelf.currentLength / weakSelf.fileLength;
weakSelf.progressLabel.text = [NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * self.currentLength / self.fileLength];
}];
}
/**
* 下载完文件之后调用:关闭文件、清空长度
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
// 关闭fileHandle
[self.fileHandle closeFile];
self.fileHandle = nil;
// 清空长度
self.currentLength = 0;
self.fileLength = 0;
}