ios 视频下载功能实现 并自动保存到相册(有MBProgressHUD 可以解开注释)
视频类定义属性
@property (nonatomic,strong) NSURLSession *session;
@property (nonatomic,strong) NSURL *url;
- (NSURLSession *)session{
if(_session == nil)
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
}
return _session;
}
- (void)download:(UIBarButtonItem *)btnItem{
_session = [XMConciseVedioPlayer getSession:_session];
[self downloadFileWithUrl:self.url];
}
- (void)downloadFileWithUrl:(NSURL *)url{
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:1.0 timeoutInterval:5.0];
[[self.session downloadTaskWithRequest:request]resume];
NSURLSessionDownloadTask *task = [_session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
NSFileManager *fileManger = [NSFileManager defaultManager];
NSString *documents = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *path = [documents stringByAppendingPathComponent:response.suggestedFilename];
[fileManger moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:nil];
UISaveVideoAtPathToSavedPhotosAlbum(path, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}];
[task resume];
}
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (!error) {
} else {
}
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float progress = (float)totalBytesWritten / totalBytesExpectedToWrite;
long pro = (long)(progress *100);
}