[iOS]如何使用AFNetworking下载文件并将其保存到文档目录

前言

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
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容