前言
iOS开发过程中,经常遇到需要缓存文件的需求(如:缓存视频、音频等)。这就需要涉及到文件下载并保存指定路径功能,这里做个记录。
功能实现:
.h文件:
#import <Foundation/Foundation.h>
#import "AFNetworking.h"
typedef void (^FileDownloadSucc)(void);
typedef void (^FileDownloadFail)(int code, NSString * desc);
NS_ASSUME_NONNULL_BEGIN
@interface SYFileManager : NSObject
+ (void)downLoadFileWithUrl:(NSString *)urlStr Path:(NSString*)path downloadProgress:(void (^)(NSProgress *downloadProgress))progress SuccessBlock:(FileDownloadSucc)success FileDownloadFail:(FileDownloadFail)failure;
@end
.m文件
#import "SYFileManager.h"
@implementation SYFileManager
/** 下载文件方法*/
+ (void)downLoadFileWithUrl:(NSString *)urlStr Path:(NSString*)path downloadProgress:(void (^)(NSProgress *downloadProgress))progress SuccessBlock:(FileDownloadSucc)success FileDownloadFail:(FileDownloadFail)failure;
{
if (urlStr.length == 0) {
return;
}
//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) {
//打印下下载进度
progress(downloadProgress);
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
//设置文件保存路径
return [NSURL fileURLWithPath:path];
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
NSLog(@"完成cache:%@",filePath);
NSHTTPURLResponse *response1 = (NSHTTPURLResponse *)response;
NSInteger statusCode = [response1 statusCode];
if (statusCode == 200) {
success();
}else{
failure(0,error.localizedFailureReason);
}
}];
//5.开始启动下载任务
[task resume];
}
@end