AFN實現文件下載

#import "ViewController.h"ide

#import "AFNetworking.h"url

 

@interface ViewController ()spa

 

@end對象

 

@implementation ViewControllerget

 

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

{it

    [self download];io

}event

 

-(void)downloadast

{

    //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

相關文章
相關標籤/搜索