//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface XPFdownload : NSObject
/// url
- (void)onVedioUrl:(NSString *)vedioUrl;
/// 成功/失败回调
@property (nonatomic, strong) BoolBlock successBlock;
@end
NS_ASSUME_NONNULL_END
//
#import "XPFdownload.h"
@interface XPFdownload ()
<
NSURLSessionDelegate
>
@property (nonatomic, strong) NSURLSessionDownloadTask *downloadTask;
@end
@implementation XPFdownload
- (void)onVedioUrl:(NSString *)vedioUrl
{
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
self.downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:vedioUrl]];
[self.downloadTask resume];
}
/// 下载完成 保存到本地相册
- (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);
//保存相册核心代码
UISaveVideoAtPathToSavedPhotosAlbum(file, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}
}
//控件本身的代理方法 更新控件样子
- (void)progressOverAndChangeViewContents {
}
//保存视频完成之后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
//NSLog(@"保存视频失败%@", error.localizedDescription);
if (self.successBlock) {
self.successBlock(NO);
}
}
else {
//NSLog(@"保存视频成功");
if (self.successBlock) {
self.successBlock(YES);
}
}
}
@end
网友评论