AFN實現文件下載


#import "ViewController.h"

#import "AFNetworking.h"

 

@interface ViewController ()

 

@end

 

@implementation ViewController

 

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event

{

    [self download];

}

 

-(void)download

{

    //1.創建會話管理者

    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];

    

    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];

    

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    

    //2.下載文件

    /*

     第一個參數:請求對象

     第二個參數:progress 進度回調 downloadProgress

     第三個參數:destination 回調(目標位置)

                有返回值

                targetPath:臨時文件路徑

                response:響應頭信息

     第四個參數:completionHandler 下載完成之后的回調

                filePath:最終的文件路徑

     */

    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        

        //監聽下載進度

        //completedUnitCount 已經下載的數據大小

        //totalUnitCount     文件數據的中大小

        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);

        

    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        

        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];

        

        NSLog(@"targetPath:%@",targetPath);

        NSLog(@"fullPath:%@",fullPath);

        

        return [NSURL fileURLWithPath:fullPath];

    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {

        

        NSLog(@"%@",filePath);

    }];

    

    //3.執行Task

    [download resume];

}

 

 

@end


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM