获取本地相册资源:PHAsset

.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;
  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,222评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,455评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,720评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,568评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,696评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,879评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,028评论 3 409
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,773评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,220评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,550评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,697评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,360评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,002评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,782评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,010评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,433评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,587评论 2 350

推荐阅读更多精彩内容

  • ## 可重入函数 ### 可重入性的理解 若一个程序或子程序可以安全的被并行执行,则称其为可重入的;即当该子程序正...
    夏至亦韵阅读 700评论 0 0
  • Ubuntu的发音 Ubuntu,源于非洲祖鲁人和科萨人的语言,发作 oo-boon-too 的音。了解发音是有意...
    萤火虫de梦阅读 99,215评论 9 467
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,149评论 2 34
  • 1.瞿依雯 家里有一只海螺。它大概有我的一只拳头那么大,还略长一些。它的外形很像一只葫芦丝。一圈又一圈不平的棱角...
    育才陈锋班阅读 665评论 0 0
  • “寒塘渡鹤影,冷月葬花魂。 落花人独立,微雨燕双飞。 水滴涟漪终消散,木记轮回恋此生。” 她时常在想,这或许也...
    简朝西阅读 447评论 0 0