美文网首页
AFNetworking实现文件断点下载

AFNetworking实现文件断点下载

作者: 邓布利多教授 | 来源:发表于2019-07-19 14:58 被阅读0次

本文为记录学习轨迹,内容抄袭自行走少年郎
这位大神

  • 因为是抄袭,所以直接上代码了,想要看细节的,可点上方链接,去查看官方的详细文档
#import "DownLoadFileController.h"

@interface DownLoadFileController ()

@property (nonatomic, strong) UIProgressView *proView;
@property (nonatomic, strong) UILabel *lProText;
@property (nonatomic, strong) UIButton *bDonwload;

/** 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 DownLoadFileController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createUI];//创建UI
    
}

/**
 * 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.proView.progress = 0.0;
                    weakSelf.lProText.text = [NSString stringWithFormat:@"当前下载进度:00.00%%"];
                } else {
                    weakSelf.proView.progress =  1.0 * weakSelf.currentLength / weakSelf.fileLength;
                    weakSelf.lProText.text = [NSString stringWithFormat:@"当前下载进度:%.2f%%",100.0 * weakSelf.currentLength / weakSelf.fileLength];
                }
                
            }];
        }];
    }
    return _downloadTask;
    
}

/**
 * 获取已下载的文件大小
 */
- (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 - 创建UI
-(void)createUI{
    
    //进度条
    [self.view addSubview:self.progressView];
    [self.proView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.top.mas_equalTo(200);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    
    //显示进度
    [self.view addSubview:self.labelText];
    [self.lProText mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(self.proView.mas_bottom).offset(10);
    }];
    
    //下载按钮
    [self.view addSubview:self.button];
    [self.bDonwload mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(90);
        make.top.mas_equalTo(self.lProText.mas_bottom).offset(20);
        make.centerX.mas_equalTo(self.view.mas_centerX);
    }];
    
}

#pragma mark - 进度条
-(UIProgressView *)progressView{
    
    if (!_proView) {
        _proView = [UIProgressView new];
    }
    return _proView;
    
}

#pragma mark - 显示进度
-(UILabel *)labelText{
    
    if (!_lProText) {
        _lProText = [UILabel new];
        _lProText.textColor = [UIColor blueColor];
        _lProText.textAlignment = NSTextAlignmentCenter;
        _lProText.font = [UIFont systemFontOfSize:14];
    }
    return _lProText;
    
}

#pragma mark - 下载按钮
-(UIButton *)button{
    
    if (!_bDonwload) {
        _bDonwload = [UIButton new];
        [_bDonwload setTitle:@"开始下载" forState:0];
        [_bDonwload setTitleColor:[UIColor whiteColor] forState:0];
        _bDonwload.titleLabel.font = [UIFont systemFontOfSize:14];
        _bDonwload.backgroundColor = [UIColor redColor];
        [_bDonwload addTarget:self action:@selector(bDLAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bDonwload;
    
}

-(void)bDLAction:(UIButton *)sender{
    
    sender.selected = !sender.isSelected;
    
    NSLog(@"sender = %@",sender.selected ? @"YES" : @"NO");
    
    if (sender.selected) { // [开始下载/继续下载]
        [sender setTitle:@"暂停下载" forState:0];
        // 沙盒文件路径
        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 {
        [sender setTitle:@"开始下载" forState:0];
        [self.downloadTask suspend];
        self.downloadTask = nil;
    }
    
}

@end

相关文章

网友评论

      本文标题:AFNetworking实现文件断点下载

      本文链接:https://www.haomeiwen.com/subject/ivxslctx.html