iOS利用AFNetworking3.0——实现文件断点下载

2020-01-18 20:21:07王冬梅

0.导入框架准备工作  

1. 将AFNetworking3.0+框架程序拖拽进项目

2. 或使用Cocopod 导入AFNetworking3.0+

3.  引入


#import "AFNetworking.h"

afnetworking断点下载,afnetworking,3.0下载,ios,afnetworking下载

afnetworking断点下载,afnetworking,3.0下载,ios,afnetworking下载

1.UI准备工作  

A. 定义一个全局的 NSURLSessionDownloadTask:下载管理句柄

由其负责所有的网络操作请求


 @interface ViewController ()

{

 // 下载句柄

 NSURLSessionDownloadTask *_downloadTask;

} 

.h文件


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

// 下载文件显示

@property (weak, nonatomic) IBOutlet UIImageView *imageView;

// 下载进度条显示

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;

@end

.m文件


@interface ViewController ()

{

 // 下载句柄

 NSURLSessionDownloadTask *_downloadTask;

} 

2.利用AFN实现文件下载操作细节  


- (void)downFileFromServer{

 //远程地址

 NSURL *URL = [NSURL URLWithString:@"http://www.easck.com/img/bdlogo.png"];

 //默认配置

 NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

 

 //AFN3.0+基于封住URLSession的句柄

 AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

 

 //请求

 NSURLRequest *request = [NSURLRequest requestWithURL:URL];

 

 //下载Task操作

 _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

  

  // @property int64_t totalUnitCount;  需要下载文件的总大小

  // @property int64_t completedUnitCount; 当前已经下载的大小

  

  // 给Progress添加监听 KVO

  NSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

  // 回到主队列刷新UI

  dispatch_async(dispatch_get_main_queue(), ^{

  // 设置进度条的百分比

 

   self.progressView.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;

  });

 

 } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

  

  //- block的返回值, 要求返回一个URL, 返回的这个URL就是文件的位置的路径

 

  NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

  NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];

  return [NSURL fileURLWithPath:path];

 

 } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

  //设置下载完成操作

  // filePath就是你下载文件的位置,你可以解压,也可以直接拿来使用

  

  NSString *imgFilePath = [filePath path];// 将NSURL转成NSString

  UIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];

  self.imageView.image = img;

 

 }];

}