[iOS]如何使用AFNetworking下載文件并將其保存到文檔目錄

前言

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
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容