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];
    
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,175评论 25 708
  • 以前听过一个家长教训孩子:你怎么能抄同学的作业呢?怎么尽给我丢脸!孩子理直气壮地说:班里好多人都抄!又不是我一个!...
    Daring_dd阅读 891评论 0 0
  • 近期目标,看到一个有上进心,努力向上奋斗的老公,看到一个更加注意健康不在熬夜玩游戏的老公,看到一个愿意和我一起学习...
    雅子12345阅读 120评论 0 1
  • 喜欢旅行,却不曾真正踏上远方,于是乎沉迷在有故事的旅行书中,想在书中从文字里感受痴迷的风土人情,于是遥远的格桑花便...
    十九kkkkkkkkk阅读 1,072评论 2 1