直接上代碼: 主要是保存到相冊(cè)
//控件 屬性
@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
{
//下載進(jìn)度
CGFloat progress = totalBytesWritten / (double)totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(), ^{
//進(jìn)行UI操作 設(shè)置進(jìn)度條
self.progressView.progressValue = progress;
self.progressView.contentLabel.text = [NSString stringWithFormat:@"%.2f%%",progress*100];
});
}
//下載完成 保存到本地相冊(cè)
- (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剩彬,保存視頻到相冊(cè)
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file)) {
//保存相冊(cè)核心代碼
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:@"商品簡(jiǎn)介已復(fù)制" forState:UIControlStateNormal];
}