美文网首页码农的日常之iOS开发iOS开发笔记
iOS下载文件和视频等多个任务

iOS下载文件和视频等多个任务

作者: FlowYourHeart | 来源:发表于2017-05-03 11:01 被阅读1750次
    #import "ViewController.h"
    #import "AFNetworking.h"
    
    
    @interface ViewController ()
    {
    // 下载任务句柄
        NSURLSessionDownloadTask *_downloadTask;
        int downIndex;
        
    }
    
    @property (weak, nonatomic) IBOutlet UIProgressView *progressV;
    
    @property (nonatomic, retain) NSArray  *urlArray;/**< 下载队列数组*/
    
    @property (nonatomic, copy) NSString  *path;/**< */
    
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        self.urlArray = @[@"https://wkbos.bdimg.com/v1/wenku57//7b98301a2adf38c28ee0aef8921fda17?responseContentDisposition=attachment%3B%20filename%3D%22IOS%BF%AA%B7%A2%BB%B7%BE%B3%B4%EE%BD%A8%BA%CD%BC%F2%B5%A5%CA%B5%C0%FD.pdf%22&responseContentType=application%2Foctet-stream&responseCacheControl=no-cache&authorization=bce-auth-v1%2Ffa1126e91489401fa7cc85045ce7179e%2F2017-04-10T06%3A38%3A37Z%2F3600%2Fhost%2Feb0754e1d269be0ad50c2ebe78cf8f78ad065150edecfd731234e5374e7e5f84&token=da145c19277039627bf70015d9f111815fe86364ba0c387344f3b5d528a7f56b&expire=2017-04-10T07:38:37Z",
                          @"https://wkbos.bdimg.com/v1/wenku39//1d6911332cc6d657237bb02776868e05?responseContentDisposition=attachment%3B%20filename%3D%22iOS%BF%AA%B7%A2%D1%A7%CF%B0-%C8%E7%BA%CE%BC%F2%B5%A5%B5%C4%B4%EE%BD%A8%BB%B7%BE%B3.pptx%22&responseContentType=application%2Foctet-stream&responseCacheControl=no-cache&authorization=bce-auth-v1%2Ffa1126e91489401fa7cc85045ce7179e%2F2017-04-10T06%3A39%3A06Z%2F3600%2Fhost%2F24de87064b7f99a34e6e3e2ee7059d0b4225a2fb8f89ada0f300fb1b9b266567&token=4dcba41dff479e826c1ac3beeb9d282f62612d0f71ca1535dd404af062c6da79&expire=2017-04-10T07:39:06Z",
                          @"http://120.25.226.186:32812/resources/videos/minion_02.mp4",
                          @"http://120.25.226.186:32812/resources/images/minion_08.png"];
        
        downIndex = 0;
        
         NSString *urlSr = self.urlArray[0];
        //准备从远程下载文件
        [self downFileFromServer:urlSr];
    
    }
    //点击开始按钮启动下载任务
    - (IBAction)beginDownLoading:(id)sender {
        //开始下载
        [_downloadTask resume];
    }
    - (IBAction)stopDownLoading:(id)sender {
        //暂停下载
        [_downloadTask suspend];
        
    }
    
    - (void)downFileFromServer:(NSString *)urlStr{
        __weak typeof(self) weakSelf = self;
        
        downIndex ++;
        if (urlStr.length <= 0) {
            //下载完成后 进行下一个任务
            if (downIndex < weakSelf.urlArray.count) {
                [weakSelf downFileFromServer:weakSelf.urlArray[downIndex]];
            }
            return ;
        }
        NSURL *URL = [NSURL URLWithString:urlStr];
        
        //默认配置
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        
        //AFN3.0+基于封住URLSession的句柄
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        //请求
        NSURLRequest *request = [NSURLRequest requestWithURL:URL];
        
        //下载Task操作
        _downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
    
            // @property int64_t totalUnitCount;     需要下载文件的总大小
            // @property int64_t completedUnitCount; 当前已经下载的大小
    //        downloadProgress.totalUnitCount;
    //        downloadProgress.completedUnitCount;
            
            // 给Progress添加监听 KVO
    
            // 回到主队列刷新UI
            dispatch_async(dispatch_get_main_queue(), ^{
                // 设置进度条的百分比
                self.progressV.progress = 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
            });
            
        } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
            
            // 要求返回一个URL, 这个URL就是文件的位置的路径
            
            NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSString *path = [cachesPath stringByAppendingPathComponent:response.suggestedFilename];
            
            NSLog(@"文件路径:%@",path);
            self.path = path;
            return [NSURL fileURLWithPath:path];
            
        } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
            //设置下载完成操作
            // filePath就是下载文件的位置, [filePath path];// 将NSURL转成NSString
     
            //下载完成后 进行下一个任务
            if (downIndex < weakSelf.urlArray.count) {
                weakSelf.progressV.progress = 0.0;
                [weakSelf downFileFromServer:weakSelf.urlArray[downIndex]];
                //开始下载
                [_downloadTask resume];
            }
           
        }];
    }
    
    
    @end
    
    
    
    

    相关文章

      网友评论

      • 不要动:下载到本地无法播放
        不要动:@FlowYourHeart NSURL *liveURL = [NSURL fileURLWithPath:@"/var/mobile/Containers/Data/Application/873AD553-9942-423E-B053-59EB321010D6/Library/Caches/new.mp4" isDirectory:YES];
        不要动:@FlowYourHeart 我是下载成功了,可是那个url放到播放器里播放不了
        FlowYourHeart:这里说的只是下载,不能播放,你查看一下下载完了没有,播放用的播放器等等其他原因
      • 皮乐皮儿:你好,请问下,缓存的视频应该放到哪里呢?是caches还是document呢?放到caches会不会因为内存不足而被清理掉?放到document,文件过大,会不会审核被拒?
        FlowYourHeart:@顾语流年 Library/Caches:
        用来存放缓存文件,iTunes不会备份此目录,此目录下的文件不会在程序退出后删除,一般存放体积比较大但又不太重要的文件
        皮乐皮儿:@FlowYourHeart 那就是可以放到cache中了?:smile:
        FlowYourHeart:@顾语流年 不会 不过像这种缓存 一定会有一个清除缓存的 功能哦
      • 易样年华:这if 能出去吗?
        FlowYourHeart:你 不能?

      本文标题:iOS下载文件和视频等多个任务

      本文链接:https://www.haomeiwen.com/subject/ousktxtx.html