ios-using afnetworking3.0+ (latest AFN)-Implement file breakpoint download

Source: Internet
Author: User
Tags uikit

0. Import Framework Preparation Work • 1. Drag and drop the afnetworking3.0+ framework program into the project ·2.  or use Cocopod to import afnetworking3.0+ 3. Introduction of #import "AFNetworking.h"

---->

1.UI Prep Work

A. Defining a global nsurlsessiondownloadtask: Download management handle It is responsible for all network operation requests.

12345 @interfaceViewController (){    // 下载句柄    NSURLSessionDownloadTask *_downloadTask;}

123456789101112131415161718 .h文件#import <UIKit/UIKit.h>@interface ViewController : UIViewController// 下载文件显示@property (weak, nonatomic) IBOutlet UIImageView *imageView;// 下载进度条显示@property (weak, nonatomic) IBOutlet UIProgressView *progressView;@end.m文件@interfaceViewController (){    // 下载句柄    NSURLSessionDownloadTask *_downloadTask;}

2. Implement file download operation details with AFN
12345678910111213141516171819202122232425262728293031323334353637383940414243444546 - (void)downFileFromServer{       //远程地址    NSURL *URL = [NSURL URLWithString:@"http://www.baidu.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;    }];}
3. With regard to the suspension and continuation
12345678 - (IBAction)stopDownloadBtnClick:(id)sender {    //暂停下载    [_downloadTask suspend];}- (IBAction)startDownloadBtnClick:(id)sender {    //开始下载    [_downloadTask resume];}
4. Detect network status-optimize user experience
12345678910111213141516171819202122 - (void)viewDidLoad {    [super viewDidLoad];       //网络监控句柄    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];       //要监控网络连接状态,必须要先调用单例的startMonitoring方法    [manager startMonitoring];       [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {        //status:        //AFNetworkReachabilityStatusUnknown          = -1,  未知        //AFNetworkReachabilityStatusNotReachable     = 0,   未连接        //AFNetworkReachabilityStatusReachableViaWWAN = 1,   3G        //AFNetworkReachabilityStatusReachableViaWiFi = 2,   无线连接        NSLog(@"%d", status);    }];       //准备从远程下载文件. -> 请点击下面开始按钮启动下载任务    [self downFileFromServer];}

>> My GitHub: Source https://github.com/saupclear/afnetworking3.0-

· AFNetworking3.0 The following version of the use of the method can see my old version of the log:

ios-using Afnetworking (AFN)-Implement file breakpoint download

Clear Saup

Source: http://www.cnblogs.com/qingche/

This article is copyright to the author and the blog Park is shared, welcome reprint, but must retain this paragraph statement, and in the article page obvious location to give the original text connection.

ios-using afnetworking3.0+ (latest AFN)-Implement file breakpoint download

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.