IOS 保存图片、视频到自定义相簿

网上有很多文章介绍了保存的图片和视频的到相簿的,几经对比和测试,效果都不如人意。经过实测和取长补短,现将重构后的参考实例粘贴如下,仅供学习和参考:

1、检测相簿以及创建相簿:

/** 创建自定义相册 */
+(void)isExistFolder:(NSString * _Nonnull)folderName
       andBackaction:(void(^ _Nullable)(PHAssetCollection * _Nullable assetCollection))backAction{
    
    __block BOOL isExists = NO;
    
    //首先获取用户手动创建相册的集合
    PHFetchResult *collectonResuts = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
    
    //对获取到集合进行遍历
    [collectonResuts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        PHAssetCollection *assetCollection = obj;
        //folderName是我们写入照片的相册
        if ([assetCollection.localizedTitle isEqualToString:folderName])  {
            isExists = YES;
            
            if (backAction) backAction(assetCollection);
        }
    }];
    
    if (!isExists) {
        if (backAction) backAction(nil);
    }
}

+(void)createFolder:(NSString *_Nonnull)folderName
      andBackaction:(void(^ _Nullable)(PHAssetCollection *_Nullable assetCollection))backAction {
    
    [Utils isExistFolder:folderName
           andBackaction:^(PHAssetCollection * _Nullable assetCollection) {
               //存在
               if (assetCollection) {
                   if (backAction) backAction(assetCollection);
               }
               //不存在
               else{
                   [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                       //添加HUD文件夹
                       [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:folderName];
                       
                   } completionHandler:^(BOOL success, NSError * _Nullable error) {
                       if (success) {
                           NSLog(@"创建相册文件夹成功!");
                           
                           [Utils isExistFolder:folderName
                                  andBackaction:^(PHAssetCollection * _Nullable assetCollection) {
                                      if (backAction) backAction(assetCollection);
                                  }];
                       } else {
                           NSLog(@"创建相册文件夹失败:%@", error);
                           if (backAction) backAction(nil);
                       }
                   }];
               }
           }];
}

上面代码需要导入系统文件 #import <Photos/Photos.h> ,并做好相册访问权限检测,实例如下:

//MARK:相册权限检测
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            if (status != PHAuthorizationStatusAuthorized) {
                NSLog(@"开启权限设置");
                //[Utils openSetting];
                return;
            }
        }];

2、保存图片到自定义相簿

//截图
    UIImage *imgQRCode = [Utils screenShotForView:self.contentView];
    
    //保存图片
    [Utils createFolder:K_APP_NAME
          andBackaction:^(PHAssetCollection *assetCollection) {
              NSLog(@"assetCollection:%@",assetCollection);
              
              dispatch_async(dispatch_get_main_queue(), ^{
                  [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                      //请求创建一个Asset
                      PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:imgQRCode];
                      
                      //请求编辑相册
                      PHAssetCollectionChangeRequest *collectonRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                      
                      //为Asset创建一个占位符,放到相册编辑请求中
                      PHObjectPlaceholder *placeHolder = [assetRequest placeholderForCreatedAsset];
                      
                      //相册中添加图片
                      [collectonRequest addAssets:@[placeHolder]];
                      
                  } completionHandler:^(BOOL success, NSError *error) {
                      if (success) {
                          NSLog(@"保存二维码成功!");
                          
                          dispatch_async(dispatch_get_main_queue(), ^{
                              [MBProgressHUD showSuccess:@"已保存到系统相册"];
                          });
                          
                      } else {
                          NSLog(@"保存二维码失败:%@", error);
                          
                          dispatch_async(dispatch_get_main_queue(), ^{
                              [MBProgressHUD showError:error.localizedDescription];
                          });
                      }
                  }];
              });
          }];

screenShotForView 为项目中生成截图的静态方法,此处设置为自己需要保存的图片 UIImage 对象即可。

K_APP_NAME 为系统的全局宏常量,此处值为当前 app名称,实际改为 相簿(相册)名称即可

/** 项目名 */
#define K_APP_NAME [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleDisplayName"]

3、保存视频到自定义相簿

//videoPath为视频下载到本地之后的本地路径
- (void)saveVideoToAlbum:(NSURL *)videoPath{
    
    __weak typeof(self) weakSelf = self;
    [Utils createFolder:K_APP_NAME
         andBackaction:^(PHAssetCollection *assetCollection) {
             NSLog(@"assetCollection:%@",assetCollection);
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
                     //请求创建一个Asset
                     PHAssetChangeRequest *assetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoPath];
                     
                     //请求编辑相册
                     PHAssetCollectionChangeRequest *collectonRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
                     
                     //为Asset创建一个占位符,放到相册编辑请求中
                     PHObjectPlaceholder *placeHolder = [assetRequest placeholderForCreatedAsset];
                     
                     //相册中添加视频
                     [collectonRequest addAssets:@[placeHolder]];
                     
                 } completionHandler:^(BOOL success, NSError *error) {
                     if (success) {
                         NSLog(@"保存视频成功!");
                         
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [MBProgressHUD showSuccess:@"视频下载成功,已保存到系统相册"];
                             
                            //刷新UI
                            //...
                         });
                         
                     } else {
                         NSLog(@"保存视频失败:%@", error);
                         
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [MBProgressHUD showError:error.localizedDescription];
                         });
                     }
                 }];
             });
    }];
}

保存图片或视频,就是里面一句代码PHAssetChangeRequest 指定不同类型,可将里面进行再次分装,已达到高效、精简便于维护的目的。

另外,如果不保存到自定义相册,一句代码就搞定了。具体可以查阅网上相关文章,本实例亲测真实有效。如有其它疑问请留言沟通交流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追夢秋陽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值