知识点1:
只能(也可能有别的步骤,不过我暂时没有想出来)先把mp4视频文件通过AFNetWorking下载到沙盒路径,(个人建议下载到NSCachesDirectory缓存下,不要放到NSDocumentDirectory下,因为cache就是用来处理缓存例如图片缓存视频缓存等,清缓存的时候也好清.)
知识点2:
再使用[PHPhotoLibrary sharedPhotoLibrary]类获取或者创建自定义相册,将下载到沙盒的视频文件写入自定义相册.
上代码:
-(void)clickDownLoad{
if ([[NSString stringWithFormat:@"%@",self.infoDic[@"videoUrl"]] containsString:@"http"]) {
}else{
[RemindView showHUDWithText:@"下载地址错误" delay:1 onView:kYBKeyWindow];
return;
}
NSString *urlstr = [NSString stringWithFormat:@"%@",self.infoDic[@"videoUrl"]];
urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlstr];
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *dateStr = [[ZYPHelper shareHelper] dateToString:[NSDate date] withDateFormat:@"YYYYMMDDHHmmSS"];
NSString *savePath = [cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp4",dateStr]];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"video/mpeg",@"video/mp4",@"audio/mp3",nil];//可下载@"text/json", @"text/javascript",@"text/html",@"video/mpeg",@"video/mp4",@"audio/mp3"等
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *fullPath = savePath;//要保存的沙盒路径
NSURLRequest *request1 = [NSURLRequest requestWithURL:url];//在线路径
self.HUD.hidden = NO;
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request1 progress:^(NSProgress *downloadProgress) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ //下载过程中由多个线程返回downloadProgress,无法给progress赋值进度,所以要选出主线程
// downloadView.observedProgress = downloadProgress;
}];
} destination:^NSURL *(NSURL *targetPath,NSURLResponse *response) {
NSString *path_sandox =NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)[0];
NSLog(@"path_sandox:%@",path_sandox);
NSString *path = [path_sandox stringByAppendingPathComponent:response.suggestedFilename];
NSLog(@"path:%@",path);
return [NSURL fileURLWithPath:fullPath];
} completionHandler:^(NSURLResponse *_Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
if(error){
self.HUD.hidden = YES;
[RemindView showHUDWithText:@"下载失败" delay:1 onView:kYBKeyWindow];
}else{
[RemindView showHUDWithText:@"下载完成" delay:1 onView:kYBKeyWindow];
[ZLPhotoManager saveVideoToAblum:[NSURL fileURLWithPath:fullPath] completion:^(BOOL suc, PHAsset *asset) {
if (suc==YES) {
dispatch_sync(dispatch_get_main_queue(), ^{
self.HUD.hidden = YES;
[RemindView showHUDWithText:@"存入相册成功!" delay:1 onView:kYBKeyWindow];
});
}else if (suc == NO){
dispatch_sync(dispatch_get_main_queue(), ^{
self.HUD.hidden = YES;
[RemindView showHUDWithText:@"存入相册失败!" delay:1 onView:kYBKeyWindow];
});
}
}];
}
}];
[task resume];
}
以上是使用第三方:
ZLPhotoManager saveVideoToAblum:是使用到的第三方,将沙盒路径的的视频写入自定义相册的的方法,ZLPhotoManager这个第三方里边功能很多(比如获取相册列表,获取视频列表等,这个比较适用于用户选择相册中的图片上传这样的功能需求),但是设置有些繁琐,自己改动的话有些麻烦,大家可以自行封装.
(友情提示写入照片到相册:UIImageWriteToSavedPhotosAlbum(cellWeak.CoverView.image, selfWeak, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)selfWeak);然后实现一个相册保存完的代理方法,判断保存失败还是成功即可)
以下是自己写的将视频导入系统相册:
将本地(不一定是沙盒,也可以是包内)视频倒入自定义相册代码如下(需要导入Photo.frame系统自带类库),可以自己封装下:
-(void)logAllAlbumName{
PHAssetCollection *desCollection;
PHFetchResult <PHAssetCollection*>*result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collect in result) {
desCollection = collect;
NSLog(@"%@",collect.localizedTitle);
}
__block NSString *colID = nil;
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
colID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"aaa"].placeholderForCreatedAssetCollection.localIdentifier;
} error:&error];
if (error) {
NSLog(@"创建相册: %@ 失败",colID);
}
NSLog(@"相册: %@ ",colID);
// [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[colID] options:nil];
__block PHObjectPlaceholder *placeholderAsset=nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest*changeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"Prepare" ofType:@"mp4"] ]];
// PHAssetChangeRequest*changeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:<#(nonnull NSURL *)#>];
placeholderAsset = changeRequest.placeholderForCreatedAsset;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAsset *asset = [[PHAsset fetchAssetsWithLocalIdentifiers:@[placeholderAsset.localIdentifier] options:nil] lastObject];
[[PHAssetCollectionChangeRequest changeRequestForAssetCollection:desCollection] addAssets:@[asset]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (success) {
NSLog(@"存入相册成功");
}
}];
}];
}
更多问题,加群讨论:565191947