AFN:使用AFN实现文件下载

Posted on 2016-07-21 16:20  柠檬片  阅读(146)  评论(0)    收藏  举报
 1 -(void)download
 2 {
 3     //1.创建会话管理者
 4     AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
 5     
 6     NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
 7     
 8     NSURLRequest *request = [NSURLRequest requestWithURL:url];
 9     
10     //2.下载文件
11     /*
12      第一个参数:请求对象
13      第二个参数:progress 进度回调 downloadProgress
14      第三个参数:destination 回调(目标位置)
15                 有返回值
16                 targetPath:临时文件路径
17                 response:响应头信息
18      第四个参数:completionHandler 下载完成之后的回调
19                 filePath:最终的文件路径
20      */
21     NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
22         
23         //监听下载进度
24         //completedUnitCount 已经下载的数据大小
25         //totalUnitCount     文件数据的中大小
26         NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
27         
28     } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
29         
30         NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
31         
32         NSLog(@"targetPath:%@",targetPath);
33         NSLog(@"fullPath:%@",fullPath);
34         
35         return [NSURL fileURLWithPath:fullPath];
36     } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
37         
38         NSLog(@"%@",filePath);
39     }];
40     
41     //3.执行Task
42     [download resume];
43 }
文件下载