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

来源:互联网 发布:技术博客rss 知乎 编辑:程序博客网 时间:2024/05/22 06:14

在iOS开发中我们如果要下载一个大的文件可能会有断点下载的需求即能够对下载任务进行暂停,之后再开始下载任务,下面即将给出利用AFNetworking进行断点下载的代码。核心思想:将下载的文件的长度记录下载,然后再次下载的时候即发送网络请求的时候在请求头中设置下载数据的位置。关键代码:

// 设置HTTP请求头中的Range

        NSString *range = [NSStringstringWithFormat:@"bytes=%zd-",self.currentLength];

        [request setValue:rangeforHTTPHeaderField:@"Range"];



全部代码:

.m文件中的代码:



#import "AFNetworkingOfflineResumeDownloadFileViewController.h"

#import <AFNetworking.h>


@interface AFNetworkingOfflineResumeDownloadFileViewController ()


/** 下载进度条 */

@property (weak,nonatomic) IBOutletUIProgressView *progressView;

/** 下载进度条Label */

@property (weak,nonatomic) IBOutletUILabel *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 {

    [superviewDidLoad];

    

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

}


/**

 * manager的懒加载

 */

- (AFURLSessionManager *)manager {

    if (!_manager) {

        NSURLSessionConfiguration *configuration = [NSURLSessionConfigurationdefaultSessionConfiguration];

        // 1. 创建会话管理者

        _manager = [[AFURLSessionManageralloc] initWithSessionConfiguration:configuration];

    }

    return_manager;

}


/**

 * downloadTask的懒加载

 */

- (NSURLSessionDataTask *)downloadTask {

    if (!_downloadTask) {

        // 创建下载URL

        NSURL *url = [NSURLURLWithString:@"http://dldir1.qq.com/qqfile/QQforMac/QQ_V5.4.0.dmg"];

        

        // 2.创建request请求

        NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];

        

        // 设置HTTP请求头中的Range

        NSString *range = [NSStringstringWithFormat:@"bytes=%zd-",self.currentLength];

        [request setValue:rangeforHTTPHeaderField:@"Range"];

        

        __weaktypeof(self) weakSelf =self;

        _downloadTask = [self.managerdataTaskWithRequest:requestcompletionHandler:^(NSURLResponse *_Nonnull response, id  _Nullable responseObject,NSError * _Nullable error) {

            NSLog(@"dataTaskWithRequest");

            

            // 清空长度

            weakSelf.currentLength =0;

            weakSelf.fileLength =0;

            

            // 关闭fileHandle

            [weakSelf.fileHandlecloseFile];

            weakSelf.fileHandle =nil;

            

        }];

        

        // 第一次收到服务器的响应的block

        [self.managersetDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session,NSURLSessionDataTask * _Nonnull dataTask,NSURLResponse * _Nonnull response) {

            NSLog(@"NSURLSessionResponseDisposition");

            if (weakSelf.currentLength){

                returnNSURLSessionResponseAllow;

            }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 = [NSFileManagerdefaultManager];

                

                if (![managerfileExistsAtPath:path]) {

                   // 如果没有下载文件的话,就创建一个文件。如果有下载文件的话,则不用重新创建(不然会覆盖掉之前的文件)

                    [manager createFileAtPath:pathcontents:nilattributes:nil];

                }

                

                // 创建文件句柄

                weakSelf.fileHandle = [NSFileHandlefileHandleForWritingAtPath:path];

                

               // 允许处理服务器的响应,才会继续接收服务器返回的数据

                returnNSURLSessionResponseAllow;

            }

            

        }];

        

        // 收到服务器返回的数据的block

        [self.managersetDataTaskDidReceiveDataBlock:^(NSURLSession *_Nonnull session, NSURLSessionDataTask * _Nonnull dataTask,NSData * _Nonnull data) {

            NSLog(@"setDataTaskDidReceiveDataBlock");

            

            // 指定数据的写入位置 --文件内容的最后面

            [weakSelf.fileHandleseekToEndOfFile];

            

            // 向沙盒写入数据

            [weakSelf.fileHandlewriteData:data];

            

            // 拼接文件总长度

            weakSelf.currentLength += data.length;

            

           // 获取主线程,不然无法正确显示进度。

            NSOperationQueue* mainQueue = [NSOperationQueuemainQueue];

            [mainQueue addOperationWithBlock:^{

                // 下载进度

                if (weakSelf.fileLength ==0) {

                    weakSelf.progressView.progress =0.0;

                    weakSelf.progressLabel.text = [NSStringstringWithFormat:@"当前下载进度:00.00%%"];

                } else {

                    weakSelf.progressView.progress1.0 * weakSelf.currentLength / weakSelf.fileLength;

                    weakSelf.progressLabel.text = [NSStringstringWithFormat:@"当前下载进度:%.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 = [selffileLengthForPath:path];

        if (currentLength >0) {  // [继续下载]

            self.currentLength = currentLength;

        }

        

        [self.downloadTaskresume];

        

    } else {

        // 暂停下载

        [self.downloadTasksuspend];

        self.downloadTask =nil;

    }

}


/**

 * 获取已下载的文件大小

 */

- (NSInteger)fileLengthForPath:(NSString *)path {

    NSInteger fileLength =0;

    NSFileManager *fileManager = [[NSFileManageralloc] init]; // default is not thread safe

    if ([fileManagerfileExistsAtPath:path]) {

        NSError *error =nil;

        NSDictionary *fileDict = [fileManagerattributesOfItemAtPath:patherror:&error];

        if (!error && fileDict) {

            fileLength = [fileDict fileSize];

        }

    }

    return fileLength;

}



@end



原创粉丝点击