// 执行下载文件的方法,可以监控下载进度
- (void)downLoadAction
{
[self.view addSubview:self.numberLabel];
// 1.创建网络管理者
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// 2.目标地址
NSURL* url = [NSURL URLWithString:@"https://img-blog.csdn.net/20160520141230950?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
__weak StartViewController* weakSelf = self;
__block NSString* cachesBlockStr = nil;
NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress* progress){
//这里监控下载进度
[weakSelf updateProgress:progress];
} destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
NSLog(@"targetPath is %@",targetPath);
//下载的目标路径
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
cachesBlockStr = cachesPath;
//path
NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
//文件存在filePath下,可以读出来放到其他文件中,后续文章会介绍
}];
// 3.启动任务,resume虽说是重新开始或继续的意思,但开始也调用这个函数
[downTask resume];
}
//更新一个label,显示百分比,label随便放位置,或者换一个更好看的控件,这个随意
-(void)updateProgress:(NSProgress*)progress{
/*
@property int64_t totalUnitCount; 需要下载文件的总大小
@property int64_t completedUnitCount; 当前已经下载的大小
*/
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
CGFloat progressf = (CGFloat)progress.completedUnitCount/(CGFloat)(progress.totalUnitCount+1);
_numberLabel.textColor = [UIColor whiteColor];
_numberLabel.backgroundColor = [UIColor colorWithWhite:0.f alpha:0.3];
progressf = progressf*100;
NSString* showStr = [NSString stringWithFormat:@"%0.f%c",progressf,'%'];
_numberLabel.text = showStr;
});
NSLog(@"%lld %lld",progress.totalUnitCount,progress.completedUnitCount);
}