前言
iOS開發(fā)過程中,經(jīng)常遇到需要緩存文件的需求(如:緩存視頻、音頻等)。這就需要涉及到文件下載并保存指定路徑功能,這里做個記錄。
功能實現(xiàn):
.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.創(chuàng)建管理者對象
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//2.確定請求的URL地址
NSURL *url = [NSURL URLWithString:urlStr];
//3.創(chuàng)建請求對象
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