iOS 最简功能的视频下载保存

直接上代码: 主要是保存到相册

//控件 属性
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *sendBtn;
@property (nonatomic, strong) CircleProgressView *progressView;
@property (nonatomic, strong) VedioDetailModel *model;
@property(nonatomic,strong)NSURLSessionDownloadTask *downloadTask;


/** 下载视频 */
- (void)startDownLoadVedioWithModel:(VedioDetailModel *)model {
    _model = model;
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    self.downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:model.vedioUrl]];
    [self.downloadTask resume];
}


#pragma mark NSSessionUrlDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //下载进度
    CGFloat progress = totalBytesWritten / (double)totalBytesExpectedToWrite;
    dispatch_async(dispatch_get_main_queue(), ^{
        //进行UI操作  设置进度条
        self.progressView.progressValue = progress;
        self.progressView.contentLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
    });
}
    //下载完成 保存到本地相册
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    //1.拿到cache文件夹的路径
    NSString *cache=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
    //2,拿到cache文件夹和文件名
    NSString *file=[cache stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    [[NSFileManager defaultManager] moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
    //3,保存视频到相册
    if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)) {
        //保存相册核心代码
        UISaveVideoAtPathToSavedPhotosAlbum(file, self, nil, nil);
    }
}

//控件本身的代理方法  更新控件样子
- (void)progressOverAndChangeViewContents {
    MyLog(@"下载完成");
    self.sendBtn.enabled = YES;
    
    self.titleBtn.enabled = NO;
    [self.titleBtn setTitle:@"视频已下载到本地" forState:UIControlStateNormal];
    self.contentBtn.enabled = NO;
    [self.contentBtn setTitle:@"商品简介已复制" forState:UIControlStateNormal];
    
}

你可能感兴趣的:(iOS 最简功能的视频下载保存)