上一篇博文我介绍了文件的上传的实现,这里我介绍一下文件的下载
//urlString服务器地址
//callBack是我写的一个block回调函数,可把结果传到另一个类中进行使用,如果实在本页面处理则不用这个block
//block进度条的回调函数
//fBlock下载后的文件的路径的回调函数
+(void)fileDownLoadWirhUrl:(NSString *)urlString jsonDictionary:(CallBack)callBack currentProgress:(Progress)block filePath:(FilePath)fBlock
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:config];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *task=[manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
//进度条
CGFloat progress=(CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount;//运算符/,当两边都是整型时,得出的结果也是整型,所以要进行类型转换
block(progress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//返回存储位置,必须用response.suggestedFilename,不能自定义文件名
NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
NSString *path = [cacheDir stringByAppendingPathComponent:response.suggestedFilename];
NSURL *fileURL = [NSURL fileURLWithPath:path];
fBlock(fileURL);
return fileURL;//注意是URL类型
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if(error){//失败
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:error.debugDescription,@"info", nil];
callBack(info,FailedType);
}else{//成功
//解析data
NSDictionary *dict=[NSDictionary dictionary];
callBack(dict,SuccessType);
}
}];
[task resume];//注意不要漏
}