//下载文件
+(void)downloadTask:(NSString*)urlStr progress:(void (^)(NSProgress * _Nonnull downloadProgress))progress completionHandler:(void(^)(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error, NSString *pathFile))completionHandler{
if (urlStr.length == 0) {
return;
}
//保存路径
NSArray *arr = [urlStr componentsSeparatedByString:@"/"];
NSString *fileName = arr.lastObject;
// 沙盒文件路径
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileName];
NSLog(@"File downloaded to: %@",path);
//1.创建管理者对象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.确定请求的URL地址
NSURL *url = [NSURL URLWithString:urlStr];
//3.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//4.下载任务
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//打印下下载进度
NSLog(@"downloadProgress = %@",downloadProgress);
if(progress){
progress(downloadProgress);
}
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//设置文件保存路径
NSLog(@"path = %@",[NSURL fileURLWithPath:path]);
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"完成cache:%@",filePath);
if(error == nil){//下载完成
if(completionHandler){
completionHandler(response,filePath,error,path);
}
}else{
NSString *message = nil;
if(error.code == -1005){
message = @"网络异常";
}else if(error.code == -1001){
message = @"请求超时";
}else{
message = @"未知错误";
}
NSLog(@"message:%@",message);
if(completionHandler){
completionHandler(response,filePath,error,@"");
}
}
}];
//5.开始启动下载任务
[task resume];
}