在iOS开发中经常会用到相册的图片,但是原生的UIImagePikerViewDelegate只能选取一张照片进行处理,这样管理起来比较麻烦,所以本次带来获取系统所有相册。
首先建一个继承NSObject的model类
.h文件中
#import <Foundation/Foundation.h>
//这里要引入系统库
#import <Photos/Photos.h>
//建一个内部类
@interface JYAblumList : NSObject
@property (nonatomic, copy) NSString *title; //相册名字
@property (nonatomic, assign) NSInteger count; //该相册内相片数量
@property (nonatomic, strong) PHAsset *headImageAsset; //相册第一张图片缩略图
@property (nonatomic, strong) PHAssetCollection *assetCollection; //相册集,通过该属性获取该相册集下所有照片
@end
@interface JYAblumTool : NSObject
+ (instancetype)sharePhotoTool;
/**
* @brief 获取用户所有相册列表
*/
- (NSArray<JYAblumList *> *)getPhotoAblumList;
/**
* @brief 获取相册内所有图片资源
* @param ascending 是否按创建时间正序排列 YES,创建时间正(升)序排列; NO,创建时间倒(降)序排列
*/
- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending;
/**
* @brief 获取指定相册内的所有图片
*/
- (NSArray<PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending;
/**
* @brief 获取每个Asset对应的图片
*/
- (void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *image))completion;
@end
.m文件中实现#import "JYAblumTool.h"
@implementation JYAblumList
@end
@implementation JYAblumTool
static JYAblumTool *sharePhotoTool = nil;
+ (instancetype)sharePhotoTool
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharePhotoTool = [[self alloc] init];
});
return sharePhotoTool;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharePhotoTool = [super allocWithZone:zone];
});
return sharePhotoTool;
}
#pragma mark - 获取所有相册列表
- (NSArray<JYAblumList *> *)getPhotoAblumList
{
NSMutableArray<JYAblumList *> *photoAblumList = [NSMutableArray array];
//获取所有智能相册
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
[smartAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL *stop) {
//过滤掉视频和最近删除
if (!([collection.localizedTitle isEqualToString:@"Recently Deleted"] ||
[collection.localizedTitle isEqualToString:@"Videos"])) {
NSArray<PHAsset *> *assets = [self getAssetsInAssetCollection:collection ascending:NO];
if (assets.count > 0) {
JYAblumList *ablum = [[JYAblumList alloc] init];
ablum.title = [self transformAblumTitle:collection.localizedTitle];
ablum.count = assets.count;
ablum.headImageAsset = assets.firstObject;
ablum.assetCollection = collection;
[photoAblumList addObject:ablum];
}
}
}];
//获取用户创建的相册
PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
[userAlbums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) {
NSArray<PHAsset *> *assets = [self getAssetsInAssetCollection:collection ascending:NO];
if (assets.count > 0) {
JYAblumList *ablum = [[JYAblumList alloc] init];
ablum.title = collection.localizedTitle;
ablum.count = assets.count;
ablum.headImageAsset = assets.firstObject;
ablum.assetCollection = collection;
[photoAblumList addObject:ablum];
}
}];
return photoAblumList;
}
- (NSString *)transformAblumTitle:(NSString *)title
{
if ([title isEqualToString:@"Slo-mo"]) {
return @"慢动作";
} else if ([title isEqualToString:@"Recently Added"]) {
return @"最近添加";
} else if ([title isEqualToString:@"Favorites"]) {
return @"最爱";
} else if ([title isEqualToString:@"Recently Deleted"]) {
return @"最近删除";
} else if ([title isEqualToString:@"Videos"]) {
return @"视频";
} else if ([title isEqualToString:@"All Photos"]) {
return @"所有照片";
} else if ([title isEqualToString:@"Selfies"]) {
return @"自拍";
} else if ([title isEqualToString:@"Screenshots"]) {
return @"屏幕快照";
} else if ([title isEqualToString:@"Camera Roll"]) {
return @"相机胶卷";
} else if ([title isEqualToString:@"Panoramas"]) {
return @"全景照片";
}
return nil;
}
- (PHFetchResult *)fetchAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
PHFetchOptions *option = [[PHFetchOptions alloc] init];
option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
return result;
}
#pragma mark - 获取相册内所有照片资源
- (NSArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending
{
NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
PHFetchOptions *option = [[PHFetchOptions alloc] init];
//ascending 为YES时,按照照片的创建时间升序排列;为NO时,则降序排列
option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];
[result enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
PHAsset *asset = (PHAsset *)obj;
[assets addObject:asset];
}];
return assets;
}
#pragma mark - 获取指定相册内的所有图片
- (NSArray<PHAsset *> *)getAssetsInAssetCollection:(PHAssetCollection *)assetCollection ascending:(BOOL)ascending
{
NSMutableArray<PHAsset *> *arr = [NSMutableArray array];
PHFetchResult *result = [self fetchAssetsInAssetCollection:assetCollection ascending:ascending];
[result enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (((PHAsset *)obj).mediaType == PHAssetMediaTypeImage) {
[arr addObject:obj];
}
}];
return arr;
}
#pragma mark - 获取asset对应的图片
- (void)requestImageForAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void (^)(UIImage *))completion
{
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
/**
resizeMode:对请求的图像怎样缩放。有三种选择:None,默认加载方式;Fast,尽快地提供接近或稍微大于要求的尺寸;Exact,精准提供要求的尺寸。
deliveryMode:图像质量。有三种值:Opportunistic,在速度与质量中均衡;HighQualityFormat,不管花费多长时间,提供高质量图像;FastFormat,以最快速度提供好的质量。
这个属性只有在 synchronous 为 true 时有效。
*/
option.resizeMode = resizeMode;//控制照片尺寸
//option.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;//控制照片质量
//option.synchronous = YES;
option.networkAccessAllowed = YES;
//param:targetSize 即你想要的图片尺寸,若想要原尺寸则可输入PHImageManagerMaximumSize
[[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
completion(image);
}];
}
@end
在ViewController里面用collectionView显示所有的图片,关于collectionView的分析前面的博客已经做了
#import "ViewController.h"
#import "Cell.h"
#import "JYAblumTool.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,retain)NSMutableArray *dataArr;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_dataArr = [[NSMutableArray alloc]init];
self.view.backgroundColor = [UIColor whiteColor];
//调用这个方法获取相册里的所有图片
[_dataArr addObjectsFromArray:[[JYAblumTool sharePhotoTool] getAllAssetInPhotoAblumWithAscending:NO]];
//此处必须要有创见一个UICollectionViewFlowLayout的对象
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init];
//同一行相邻两个cell的最小间距
layout.minimumInteritemSpacing = 5;
//最小两行之间的间距
layout.minimumLineSpacing = 5;
_collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 375, 667) collectionViewLayout:layout];
_collectionView.backgroundColor=[UIColor whiteColor];
_collectionView.delegate=self;
_collectionView.dataSource=self;
//这个是横向滑动
//layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
[self.view addSubview:_collectionView];
/*
*这是重点 必须注册cell
*/
//这种是xib建的cell 需要这么注册
UINib *cellNib=[UINib nibWithNibName:@"Cell" bundle:nil];
[_collectionView registerNib:cellNib forCellWithReuseIdentifier:@"Cell"];
}
//一共有多少个组
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
//每一组有多少个cell
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return _dataArr.count;
}
//每一个cell是什么
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
Cell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
PHAsset *asset = _dataArr[indexPath.row];
[self getImageWithAsset:asset completion:^(UIImage *image) {
cell.backgroundColor = [UIColor whiteColor];
cell.headerImageVIew.image=image;
}];
return cell;
}
//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(115, 100);
}
//从这个回调中获取所有的图片
- (void)getImageWithAsset:(PHAsset *)asset completion:(void (^)(UIImage *image))completion
{
CGSize size = [self getSizeWithAsset:asset];
[[JYAblumTool sharePhotoTool] requestImageForAsset:asset size:size resizeMode:PHImageRequestOptionsResizeModeFast completion:completion];
}
#pragma mark - 获取图片及图片尺寸的相关方法
- (CGSize)getSizeWithAsset:(PHAsset *)asset
{
CGFloat width = (CGFloat)asset.pixelWidth;
CGFloat height = (CGFloat)asset.pixelHeight;
CGFloat scale = width/height;
return CGSizeMake(self.collectionView.frame.size.height*scale, self.collectionView.frame.size.height);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
下面是结果图
大家好,我叫mark 这次总结的是如何获取系统相册的图片,下次我将分析,如何用coreData存储这些图片,欢迎大家多多与我交流。