前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS开发中利用AFNetworking进行断点下载

iOS开发中利用AFNetworking进行断点下载

作者头像
用户1451823
发布2018-09-13 15:29:14
9080
发布2018-09-13 15:29:14
举报
文章被收录于专栏:DannyHoo的专栏DannyHoo的专栏

版权声明:本文为博主原创文章,未经博主允许不得转载。 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

  • (void)viewDidLoad {

    super viewDidLoad;

self.navigationItem.title = @"AFNetworking断点下载(支持离线)";

}

/**

 * 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;

        }];

// 第一次收到服务器的响应的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断点下载(支持离线)

 */

  • (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;

}

@end

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年07月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档