iOS視頻下載功能實現,并自動保存到相冊(有MBProgressHUD 可以解開注釋),供大家參考,具體內容如下
視頻類定義屬性
///@property (nonatomic,strong) MBProgressHUD *hud;@property (nonatomic,strong) NSURLSession *session;///視頻播放和下載用的url @property (nonatomic,strong) NSURL *url;
///初始化session- (NSURLSession *)session{ if(_session == nil) { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; } return _session;}///下載- (void)download:(UIBarButtonItem *)btnItem{ ///初始化Session _session = [XMConciseVedioPlayer getSession:_session]; ///self.hud = [MBProgressHUD showHUDAddedTo:self animated:YES]; [self downloadFileWithUrl:self.url]; }///通過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) { ///[self.hud setLabelText:[NSString stringWithFormat:@"下載成功"]]; NSFileManager *fileManger = [NSFileManager defaultManager]; ///沙盒Documents路徑 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) { ///[self.hud setLabelText:[NSString stringWithFormat:@"保存到相冊成功"]]; } else { ///[self.hud setLabelText:[NSString stringWithFormat:@"下載失敗"]]; } ///[self.hud hide:YES afterDelay:3.0];}// 進度數據- (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); ///[self.hud setLabelText:[NSString stringWithFormat:@"下載進度:%ld%%",pro]];}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答