您好,登錄后才能下訂單哦!
小編給大家分享一下iOS如何實現視頻下載并自動保存到相冊功能,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
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]]; }
看完了這篇文章,相信你對“iOS如何實現視頻下載并自動保存到相冊功能”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。