本文主要是介绍AFN3.0续点下载,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
首先需要把AFN3.0导入到项目中
#import "ViewController.h"
#import "AFNetworking.h"@interface ViewController ()
{// 下载操作NSURLSessionDownloadTask *_downloadTask;
}
@end@implementation ViewController- (void)downFileFromServer{NSURL *URL = [NSURL URLWithString:@"http://p1.pichost.me/i/40/1639665.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添加监听 KVONSLog(@"%f",1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);// 回到主队列刷新UIdispatch_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转成NSStringUIImage *img = [UIImage imageWithContentsOfFile:imgFilePath];self.imageView.image = img;}];
}- (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(@"%ld", (long)status);}];//准备从远程下载文件. -> 请点击下面开始按钮启动下载任务[self downFileFromServer];}
- (IBAction)stopDownloadBtnClick:(id)sender {//暂停下载[_downloadTask suspend];
}
- (IBAction)startDownloadBtnClick:(id)sender {//开始下载[_downloadTask resume];
}@end
这篇关于AFN3.0续点下载的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!