獲取本地相冊資源:PHAsset

.m 文件

 引入相應(yīng)庫文件 :

    #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)();
    靜態(tài)全局屬性,其實(shí)可以寫入單例。Swift中我已轉(zhuǎn)向單例
    staticCGRectoldFrame;
    staticUIView*backView;

    @interfaceLocalImageHelper :NSObject
    @property(assign,nonatomic)NSIntegertype;

獲取全部相冊資源
+ (NSMutableArray*) GetPhotoListDatas;

獲取某一個相冊的結(jié)果集
+ (PHFetchResult*) GetFetchResult:(PHAssetCollection*)asset;

獲取圖片實(shí)體,并把圖片結(jié)果存放到數(shù)組中,返回值數(shù)組
+ (NSMutableArray*) GetPhotoAssets:(PHFetchResult*)fetchResult;

只獲取相機(jī)膠卷結(jié)果集
+ (PHFetchResult*) GetCameraRollFetchResul;

回調(diào)方法使用數(shù)組
+ (void) GetImageObject:(id)asset complection:(void(^)(UIImage*,BOOLisDegraded))complection;

PHAsset轉(zhuǎn)image<非高清>
+ (NSMutableArray*)loadPhotoDataArray:(NSMutableArray*)array;

PHAsset轉(zhuǎn)image<高清>
+ (NSMutableArray*)loadPhotoHightQualityDataArray:(NSMutableArray*)array;

獲取訪問本地相冊權(quán)限的狀態(tài)值
+ (void)getStatusForAssetLibraryViewController:(UIViewController*)viewController success:(StatusBlock)success;

添加照片時,標(biāo)記按鈕小動畫
+ (void) roundAnimation:(UILabel*)label;
+ (void) selectAnimation:(UIButton*)button;

點(diǎn)擊小圖片,展示大圖片
+ (void)showImageView:(UIImageView*)imageV viewController:(UIViewController*)viewController;

相機(jī)訪問權(quán)限
+ (void)getCameraAuthorStatusWithViewController:(UIViewController*)viewController success:(StatusBlock)success;

生成純色圖
+ (UIImage*)imageWithColor:(UIColor*)color;

.h文件

獲取所有圖片活視頻數(shù)據(jù)

+ (NSMutableArray *)GetPhotoListDatas
{

    NSMutableArray *dataArray = [NSMutableArray array];

    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc]init];
//最近添加,連拍,相機(jī)膠卷,屏幕快照,自拍,全景
    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;
        數(shù)組中存儲model(相冊類型、相冊圖片數(shù)量、item)
        [dataArray addObject:[LocalImageHelper setupModelWith:item]];
}



//自定義相冊
    PHFetchResult *smartAlbumsFetchResult1 = [PHAssetCollection fetchTopLevelUserCollectionsWithOptions:fetchOptions];

    for (PHAssetCollection *sub in smartAlbumsFetchResult1)
    {
        [dataArray addObject:[LocalImageHelper setupModelWith:sub]];
    }

    return dataArray;
}

轉(zhuǎn)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) {
    //只添加圖片類型資源,去除視頻類型資源
   //當(dāng)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;
}

獲取本機(jī)訪問權(quán)限
+ (void)getStatusForAssetLibraryViewController:(UIViewController*)viewController success:(StatusBlock)success {
//無權(quán)限
 NSDictionary*infoDictionary = [[NSBundlemainBundle]infoDictionary];
// app名稱
 NSString*app_Name = [infoDictionaryobjectForKey:@"CFBundleDisplayName"];
 ALAuthorizationStatusauthorzationStatus = [ALAssetsLibraryauthorizationStatus];
 if(authorzationStatus ==ALAuthorizationStatusDenied|| authorzationStatus ==ALAuthorizationStatusRestricted) {
   [AlertViewHelperssetAlertWithViewController:viewControllerTitle:@"提示"message:[NSStringstringWithFormat:@"請?jiān)趇Phone的“設(shè)置->隱私->通訊錄”允許<%@>訪問你的手機(jī)相冊",app_Name]cancelTitle:@"取消"sureTitle:@"確定"cancle:^{
 }sure:^{
     NSURL*setUrl = [NSURLURLWithString:@"prefs:root=Privacy"];
     [[UIApplicationsharedApplication]openURL:setUrl];
    }];
}else if(authorzationStatus ==ALAuthorizationStatusNotDetermined){
  //本應(yīng)用首次訪問請求授權(quán)
 [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];
     }];
 }

相機(jī)訪問權(quán)限
+ (void)getCameraAuthorStatusWithViewController:(UIViewController*)viewController success:(StatusBlock)success {
 //無權(quán)限
   NSDictionary*infoDictionary = [[NSBundlemainBundle]infoDictionary];
// app名稱
   NSString*app_Name = [infoDictionaryobjectForKey:@"CFBundleDisplayName"];
   AVAuthorizationStatusauthorzationStatus = [AVCaptureDeviceauthorizationStatusForMediaType:AVMediaTypeVideo];
  if(authorzationStatus ==ALAuthorizationStatusDenied|| authorzationStatus ==ALAuthorizationStatusRestricted) {
    [AlertViewHelperssetAlertWithViewController:viewControllerTitle:@"提示"message:[NSStringstringWithFormat:@"請?jiān)趇Phone的“設(shè)置->隱私->通訊錄”允許<%@>訪問你的手機(jī)相機(jī)",app_Name]cancelTitle:@"取消"sureTitle:@"確定"cancle:^{
     }sure:^{
          NSURL*setUrl = [NSURLURLWithString:@"prefs:root=Privacy"];
          [[UIApplicationsharedApplication]openURL:setUrl];
     }];
  }elseif(authorzationStatus ==ALAuthorizationStatusNotDetermined){
 //本應(yīng)用首次訪問請求授權(quán)
   [AVCaptureDevicerequestAccessForMediaType:AVMediaTypeVideocompletionHandler:^(BOOLgranted) {
       if(granted) {
           success();
       }else{
            [AlertViewHelpersshowViewAtBottomWithViewController:viewControllerstring:@"授權(quán)失敗"];
     }
     }];
      }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;
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • ## 可重入函數(shù) ### 可重入性的理解 若一個程序或子程序可以安全的被并行執(zhí)行,則稱其為可重入的;即當(dāng)該子程序正...
    夏至亦韻閱讀 728評論 0 0
  • Ubuntu的發(fā)音 Ubuntu,源于非洲祖魯人和科薩人的語言,發(fā)作 oo-boon-too 的音。了解發(fā)音是有意...
    螢火蟲de夢閱讀 99,571評論 9 467
  • linux資料總章2.1 1.0寫的不好抱歉 但是2.0已經(jīng)改了很多 但是錯誤還是無法避免 以后資料會慢慢更新 大...
    數(shù)據(jù)革命閱讀 12,228評論 2 33
  • 1.瞿依雯 家里有一只海螺。它大概有我的一只拳頭那么大,還略長一些。它的外形很像一只葫蘆絲。一圈又一圈不平的棱角...
    育才陳鋒班閱讀 697評論 0 0
  • “寒塘渡鶴影,冷月葬花魂。 落花人獨(dú)立,微雨燕雙飛。 水滴漣漪終消散,木記輪回戀此生。” 她時常在想,這或許也...
    簡朝西閱讀 470評論 0 0