美文网首页iOS 知识点
获取本地相册资源:PHAsset

获取本地相册资源:PHAsset

作者: SMFly | 来源:发表于2016-08-12 10:10 被阅读1710次

    .m 文件

     引入相应库文件 :
    
        #import <Foundation/Foundation.h >
        #import < AssetsLibrary/ALAsset.h>
        #import < AssetsLibrary/ALAssetsLibrary.h>
        #import < AssetsLibrary/ALAssetsGroup.h>
        #import < AssetsLibrary/ALAssetRepresentation.h>
        #import <Photos/Photos.h>
        #import <AVFoundation/AVFoundation.h>
        #import <UIKit/UIKit.h>
    
        typedefvoid(^StatusBlock)();
        静态全局属性,其实可以写入单例。Swift中我已转向单例
        staticCGRectoldFrame;
        staticUIView*backView;
    
        @interfaceLocalImageHelper :NSObject
        @property(assign,nonatomic)NSIntegertype;
    
    获取全部相册资源
    + (NSMutableArray*) GetPhotoListDatas;
    
    获取某一个相册的结果集
    + (PHFetchResult*) GetFetchResult:(PHAssetCollection*)asset;
    
    获取图片实体,并把图片结果存放到数组中,返回值数组
    + (NSMutableArray*) GetPhotoAssets:(PHFetchResult*)fetchResult;
    
    只获取相机胶卷结果集
    + (PHFetchResult*) GetCameraRollFetchResul;
    
    回调方法使用数组
    + (void) GetImageObject:(id)asset complection:(void(^)(UIImage*,BOOLisDegraded))complection;
    
    PHAsset转image<非高清>
    + (NSMutableArray*)loadPhotoDataArray:(NSMutableArray*)array;
    
    PHAsset转image<高清>
    + (NSMutableArray*)loadPhotoHightQualityDataArray:(NSMutableArray*)array;
    
    获取访问本地相册权限的状态值
    + (void)getStatusForAssetLibraryViewController:(UIViewController*)viewController success:(StatusBlock)success;
    
    添加照片时,标记按钮小动画
    + (void) roundAnimation:(UILabel*)label;
    + (void) selectAnimation:(UIButton*)button;
    
    点击小图片,展示大图片
    + (void)showImageView:(UIImageView*)imageV viewController:(UIViewController*)viewController;
    
    相机访问权限
    + (void)getCameraAuthorStatusWithViewController:(UIViewController*)viewController success:(StatusBlock)success;
    
    生成纯色图
    + (UIImage*)imageWithColor:(UIColor*)color;
    

    .h文件

    获取所有图片活视频数据
    
    + (NSMutableArray *)GetPhotoListDatas
    {
    
        NSMutableArray *dataArray = [NSMutableArray array];
    
        PHFetchOptions *fetchOptions = [[PHFetchOptions alloc]init];
    //最近添加,连拍,相机胶卷,屏幕快照,自拍,全景
        NSArray *array = @[@(PHAssetCollectionSubtypeSmartAlbumRecentlyAdded),@(PHAssetCollectionSubtypeSmartAlbumBursts),@(PHAssetCollectionSubtypeSmartAlbumUserLibrary),@(PHAssetCollectionSubtypeSmartAlbumScreenshots),@(PHAssetCollectionSubtypeSmartAlbumSelfPortraits),@(PHAssetCollectionSubtypeSmartAlbumPanoramas)];
    
    //智能相册
    
        for (NSNumber *itemNum in array) {
            
            PHFetchResult *smartAlbumsFetchResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype: [itemNum integerValue] options:fetchOptions];
            
            PHAssetCollection *item = smartAlbumsFetchResult.firstObject;
            数组中存储model(相册类型、相册图片数量、item)
            [dataArray addObject:[LocalImageHelper setupModelWith:item]];
    }
    
    
    
    //自定义相册
        PHFetchResult *smartAlbumsFetchResult1 = [PHAssetCollection fetchTopLevelUserCollectionsWithOptions:fetchOptions];
    
        for (PHAssetCollection *sub in smartAlbumsFetchResult1)
        {
            [dataArray addObject:[LocalImageHelper setupModelWith:sub]];
        }
    
        return dataArray;
    }
    
    转model存储(相册资源还是collection)
    + (LocalImageModel *)setupModelWith:(PHAssetCollection *)item {
        PHFetchResult *group = [PHAsset fetchAssetsInAssetCollection:item options:nil];
    
        LocalImageModel *model = [LocalImageModel new];
        model.title = item.localizedTitle;
        model.count = group.count;
        model.collection = item;
    
    return model;
    }
    
    获取图片类型资源PHAsset
    + (NSMutableArray*)GetPhotoAssets:(PHFetchResult*)fetchResult
    {
        NSMutableArray*dataArray = [NSMutableArrayarray];
        for(PHAsset*assetinfetchResult) {
        //只添加图片类型资源,去除视频类型资源
       //当mediaType == 2时,这个资源则为视频资源
       if(asset.mediaType==1) {
          [dataArrayaddObject:asset];
        }
     }
    returndataArray;
    }
    
    
    + (PHFetchResult*)GetCameraRollFetchResul
    {
       PHFetchOptions*fetchOptions = [[PHFetchOptionsalloc]init];
    
       PHFetchResult*smartAlbumsFetchResult = [PHAssetCollectionfetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbumsubtype:PHAssetCollectionSubtypeSmartAlbumUserLibraryoptions:fetchOptions];
    
       PHFetchResult*fetch = [PHAssetfetchAssetsInAssetCollection:[smartAlbumsFetchResultobjectAtIndex:0]options:nil];
    
       returnfetch;
    }
    
    + (void)GetImageObject:(id)asset complection:(void(^)(UIImage*,BOOLisDegraded))complection
    {
       if([assetisKindOfClass:[PHAssetclass]]) {
           PHAsset*phAsset = (PHAsset*)asset;
           CGFloatphotoWidth = [UIScreenmainScreen].bounds.size.width;
           CGFloataspectRatio = phAsset.pixelWidth/ (CGFloat)phAsset.pixelHeight;
           CGFloatmultiple = [UIScreenmainScreen].scale;
           CGFloatpixelWidth = photoWidth * multiple;
           CGFloatpixelHeight = pixelWidth / aspectRatio;
           [[PHImageManager defaultManager] requestImageForAsset:phAsset targetSize:CGSizeMake(pixelWidth, pixelHeight)contentMode:PHImageContentModeAspectFit options:nilresultHandler:^(UIImage*_Nullableresult,NSDictionary*_Nullableinfo) {
                BOOLdownloadFinined = (![[infoobjectForKey:PHImageCancelledKey]boolValue] && ![infoobjectForKey:PHImageErrorKey]);
                if(downloadFinined) {
                if(complection) complection(result,[[infoobjectForKey:PHImageResultIsDegradedKey]boolValue]);
             }
           }];
       }
     }
    
    
    + (NSMutableArray*)loadPhotoHightQualityDataArray:(NSMutableArray*)array
    {
          NSMutableArray*tempArray = [NSMutableArrayarray];
          PHImageRequestOptions*options = [[PHImageRequestOptionsalloc]init];
         //options.resizeMode = PHImageRequestOptionsResizeModeExact;
         options.synchronous=YES;
        if(array.count) {
           for(PHAsset*iteminarray) {
             [[PHImageManager defaultManager]requestImageForAsset:itemtargetSize:PHImageManagerMaximumSizecontentMode:PHImageContentModeDefaultoptions:optionsresultHandler:^(UIImage*result,NSDictionary*info){
                   [tempArrayaddObject:result];
            }];
        }
     }
     returntempArray;
    }
    
    获取本机访问权限
    + (void)getStatusForAssetLibraryViewController:(UIViewController*)viewController success:(StatusBlock)success {
    //无权限
     NSDictionary*infoDictionary = [[NSBundlemainBundle]infoDictionary];
    // app名称
     NSString*app_Name = [infoDictionaryobjectForKey:@"CFBundleDisplayName"];
     ALAuthorizationStatusauthorzationStatus = [ALAssetsLibraryauthorizationStatus];
     if(authorzationStatus ==ALAuthorizationStatusDenied|| authorzationStatus ==ALAuthorizationStatusRestricted) {
       [AlertViewHelperssetAlertWithViewController:viewControllerTitle:@"提示"message:[NSStringstringWithFormat:@"请在iPhone的“设置->隐私->通讯录”允许<%@>访问你的手机相册",app_Name]cancelTitle:@"取消"sureTitle:@"确定"cancle:^{
     }sure:^{
         NSURL*setUrl = [NSURLURLWithString:@"prefs:root=Privacy"];
         [[UIApplicationsharedApplication]openURL:setUrl];
        }];
    }else if(authorzationStatus ==ALAuthorizationStatusNotDetermined){
      //本应用首次访问请求授权
     [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatusstatus) {
     if(status ==ALAuthorizationStatusAuthorized) {
     success();
         }
       }];
     }else{
        success();
     }
    }
    
    
    + (void) roundAnimation:(UILabel*)label {
         CAKeyframeAnimation* animation = [LocalImageHelpergetAnimationStyle];
         [label.layeraddAnimation:animationforKey:nil];
    }
    + (void) selectAnimation:(UIButton*)button {
        CAKeyframeAnimation* animation = [LocalImageHelpergetAnimationStyle];
        [button.layeraddAnimation:animationforKey:nil];
     }
    
    + (CAKeyframeAnimation*)getAnimationStyle {
          CAKeyframeAnimation* animation = [CAKeyframeAnimationanimationWithKeyPath:@"transform"];
         animation.duration=0.5;
         NSMutableArray*values = [NSMutableArrayarray];
         [valuesaddObject:[NSValuevalueWithCATransform3D:CATransform3DMakeScale(0.1,0.1,1.0)]];
         [valuesaddObject:[NSValuevalueWithCATransform3D:CATransform3DMakeScale(1.2,1.2,1.0)]];
         [valuesaddObject:[NSValuevalueWithCATransform3D:CATransform3DMakeScale(0.9,0.9,1.0)]];
         [valuesaddObject:[NSValuevalueWithCATransform3D:CATransform3DMakeScale(1.0,1.0,1.0)]];
         animation.values= values;
         returnanimation;
     }
    
    放大,缩放,保存 
    + (void)showImageView:(UIImageView*)imageV viewController:(UIViewController*)viewController {
       if(!imageV.image) {
       return;
       }
      UIWindow*window = [UIApplicationsharedApplication].keyWindow;
      UIView*backgroundView = [[UIViewalloc]initWithFrame:CGRectMake(0,0, [UIScreenmainScreen].bounds.size.width, [UIScreenmainScreen].bounds.size.height)];
      oldFrame= [imageVconvertRect:imageV.boundstoView:window];
      backgroundView.backgroundColor= [UIColorblackColor];
      backgroundView.alpha=0;
      UIImageView*imageView = [[UIImageViewalloc]initWithFrame:oldFrame];
      imageView.image= imageV.image;
      imageView.tag=3000;
      [backgroundViewaddSubview:imageView];
      backView= backgroundView;
      [windowaddSubview:backgroundView];
      UIButton*button = [UIButtonbuttonWithType:UIButtonTypeCustom];
      button.frame=CGRectMake(ScreenWidth-40,27,30,30);
      [buttonsetImage:[UIImageimageNamed:@"saveImage.png"]forState:UIControlStateNormal];
      [buttonsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];
      [button addTarget:selfaction:@selector(savePicToLocal:)forControlEvents:UIControlEventTouchUpInside];
      UITapGestureRecognizer*tap = [[UITapGestureRecognizeralloc]initWithTarget:selfaction:@selector(hideImage:)];
      UIButton*buttonC = [UIButtonbuttonWithType:UIButtonTypeCustom];
      buttonC.frame=CGRectMake(10,27,70,30);
      [buttonCsetImage:[UIImageimageNamed:@"jiankuohao2.png"]forState:UIControlStateNormal];
      [buttonCsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];
      [buttonC addTarget:selfaction:@selector(hideImage:)forControlEvents:UIControlEventTouchUpInside];
      [backgroundViewaddSubview:buttonC];
      [backgroundViewaddSubview:button];
      [backgroundViewaddGestureRecognizer: tap];
      [UIViewanimateWithDuration:0.3animations:^{
        imageView.frame=CGRectMake(0,([UIScreenmainScreen].bounds.size.height-    imageV.image.size.height*    [UIScreenmainScreen].bounds.size.width/imageV.image.size.width)/2, [UIScreenmainScreen].bounds.size.width, imageV.image.size.height*[UIScreenmainScreen].bounds.size.width/imageV.image.size.width);
        backgroundView.alpha=1;
       }completion:^(BOOLfinished) {
      }];
    }
    
    + (void)savePicToLocal:(UIButton*)sender {
      UIImageView*imageView = (UIImageView*)[sender.superviewviewWithTag:3000];
      UIImageWriteToSavedPhotosAlbum(imageView.image,self,@selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:),nil);
    }
    + (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
       if(!error) {
          UILabel*label = [[UILabelalloc]initWithFrame:CGRectMake(0,0,100,30)];
          label.center=backView.center;
          [backViewaddSubview:label];
          label.layer.masksToBounds=YES;
          label.layer.cornerRadius=5;
          label.text=@"保存成功";
          label.font= [UIFontsystemFontOfSize:14];
          label.textColor= [UIColorblackColor];
          label.textAlignment=NSTextAlignmentCenter;
          label.backgroundColor= [UIColorgroupTableViewBackgroundColor];
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
             [labelremoveFromSuperview];
          });
        }else{
            UILabel*label = [[UILabelalloc]initWithFrame:CGRectMake(0,0,100,30)];
            label.center=backView.center;
            [backViewaddSubview:label];
            label.font= [UIFontsystemFontOfSize:14];
             label.textColor= [UIColorblackColor];
            label.textAlignment=NSTextAlignmentCenter;
           label.backgroundColor= [UIColorgroupTableViewBackgroundColor];
           label.text=@"保存失败";
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0*NSEC_PER_SEC)),dispatch_get_main_queue(), ^{
           [labelremoveFromSuperview];
         });
        }
     }
    
    + (void)hideImage:(UITapGestureRecognizer*)tap{
     UIImageView*imageView = (UIImageView*)[backViewviewWithTag:3000];
         [UIViewanimateWithDuration:0.3animations:^{
                imageView.frame=oldFrame;
                backView.alpha=0;
          }completion:^(BOOLfinished) {
                [backViewremoveFromSuperview];
         }];
     }
    
    相机访问权限
    + (void)getCameraAuthorStatusWithViewController:(UIViewController*)viewController success:(StatusBlock)success {
     //无权限
       NSDictionary*infoDictionary = [[NSBundlemainBundle]infoDictionary];
    // app名称
       NSString*app_Name = [infoDictionaryobjectForKey:@"CFBundleDisplayName"];
       AVAuthorizationStatusauthorzationStatus = [AVCaptureDeviceauthorizationStatusForMediaType:AVMediaTypeVideo];
      if(authorzationStatus ==ALAuthorizationStatusDenied|| authorzationStatus ==ALAuthorizationStatusRestricted) {
        [AlertViewHelperssetAlertWithViewController:viewControllerTitle:@"提示"message:[NSStringstringWithFormat:@"请在iPhone的“设置->隐私->通讯录”允许<%@>访问你的手机相机",app_Name]cancelTitle:@"取消"sureTitle:@"确定"cancle:^{
         }sure:^{
              NSURL*setUrl = [NSURLURLWithString:@"prefs:root=Privacy"];
              [[UIApplicationsharedApplication]openURL:setUrl];
         }];
      }elseif(authorzationStatus ==ALAuthorizationStatusNotDetermined){
     //本应用首次访问请求授权
       [AVCaptureDevicerequestAccessForMediaType:AVMediaTypeVideocompletionHandler:^(BOOLgranted) {
           if(granted) {
               success();
           }else{
                [AlertViewHelpersshowViewAtBottomWithViewController:viewControllerstring:@"授权失败"];
         }
         }];
          }else{
         success();
        }
    }
      去线,主要祛除,tabbar和navigatonBar的线。不过navigationbar祛除黑线后,背景会变透明,
      + (UIImage*)imageWithColor:(UIColor*)color
      {
         CGRectrect =CGRectMake(0,0,ScreenWidth,49);
         UIGraphicsBeginImageContext(rect.size);
         CGContextRefcontext =UIGraphicsGetCurrentContext();
         CGContextSetFillColorWithColor(context,color.CGColor);
         CGContextFillRect(context, rect);
         UIImage*img =UIGraphicsGetImageFromCurrentImageContext();
         UIGraphicsEndImageContext();
         returnimg;
      }

    相关文章

      网友评论

        本文标题:获取本地相册资源:PHAsset

        本文链接:https://www.haomeiwen.com/subject/gewssttx.html