首先我们简单的了解一下框架的二结构
这里面大家只需要关注
//获取胶卷相册
- (void)getCameraRollAlbum:(BOOL)allowPickingVideo allowPickingImage:(BOOL)allowPickingImage completion:(void (^)(AlbumModel *model))completion{
__block AlbumModel *model;
if (iOS8Later) {
PHFetchOptions *options = [[PHFetchOptions alloc] init];
if (!allowPickingVideo) options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",PHAssetMediaTypeImage];
if (!allowPickingImage) options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",PHAssetMediaTypeVideo];
PHFetchResult *results= [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in results) {
// 有可能是PHCollectionList类的的对象,过滤掉
if (![collection isKindOfClass:[PHAssetCollection class]]) continue;
if ([self isCameraRollAlbum:collection.localizedTitle]) {
PHFetchResult *assetResult = [PHAsset fetchAssetsInAssetCollection:collection options:options];
model = [self modelWithResult:assetResult albumName:collection.localizedTitle];
if (completion) {
completion(model);
}
break;
}
}
}else{
[self.assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
NSString *name = [group valueForProperty:ALAssetsGroupPropertyName];
if ([self isCameraRollAlbum:name]) {
model = [self modelWithResult:group albumName:name];
if (completion) {
completion(model);
}
*stop = YES;
}
} failureBlock:nil];
}
}
//获取所有相册
- (void)getAllAlbums:(BOOL)allowPickingVideo allowPickingImage:(BOOL)allowPickingImage completion:(void (^)(NSArray<AlbumModel *> *models))completion{
NSMutableArray *albumArray = [[NSMutableArray alloc] initWithCapacity:0];
if (iOS8Later) {
PHFetchOptions *options = [[PHFetchOptions alloc] init];
if (!allowPickingVideo) {
options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",PHAssetMediaTypeImage];
}
if (!allowPickingImage) {
options.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld",PHAssetMediaTypeAudio];
}
PHFetchResult *myPhotoStreamAlbum = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumMyPhotoStream options:nil];
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
PHFetchResult *topLevelUserCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
PHFetchResult *syncedAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumSyncedAlbum options:nil];
PHFetchResult *sharedAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumCloudShared options:nil];
NSArray *allAlbums = @[myPhotoStreamAlbum,smartAlbums,topLevelUserCollections,syncedAlbums,sharedAlbums];
for (PHFetchResult *fetchResult in allAlbums) {
for (PHAssetCollection *collection in fetchResult) {
if (![collection isKindOfClass:[PHAssetCollection class]]) {
continue;
}
PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:options];
if (fetchResult.count < 1) continue;
if ([self isCameraRollAlbum:collection.localizedTitle]) {
[albumArray insertObject:[self modelWithResult:fetchResult albumName:collection.localizedTitle] atIndex:0];
}else{
[albumArray addObject:[self modelWithResult:fetchResult albumName:collection.localizedTitle]];
}
}
}
if (completion && albumArray.count > 0) {
completion(albumArray);
}
}else{
[self.assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (!group) {
if (completion && albumArray.count > 0) {
completion(albumArray);
}
}
if ([group numberOfAssets] < 1) return ;
NSString *name = [group valueForProperty:ALAssetsGroupPropertyName];
if ([self isCameraRollAlbum:name]) {
[albumArray insertObject:[self modelWithResult:group albumName:name] atIndex:0];
}else if([name isEqualToString:@"My Photo Stream"] || [name isEqualToString:@"我的照片流"]){
if (albumArray.count > 0) {
[albumArray insertObject:[self modelWithResult:group albumName:name] atIndex:1];
}else{
[albumArray addObject:[self modelWithResult:group albumName:name]];
}
}else{
[albumArray addObject:[self modelWithResult:group albumName:name]];
}
} failureBlock:nil];
}
}
//获取指定相册里面的相片或视屏文件
- (void)getAssetsFromFetchResult:(id)result allowPickingVideo:(BOOL)allowPickingVideo allowPickingImage:(BOOL)allowPickingImage completion:(void (^)(NSArray<AssetModel *> *models))completion{
NSMutableArray *photoArray = [NSMutableArray array];
if ([result isKindOfClass:[PHFetchResult class]]) {
PHFetchResult *fetch = (PHFetchResult *)result;
[fetch enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
AssetModel *model = [self assetModelWithAsset:obj allowPickingVideo:allowPickingVideo allowPickingImage:allowPickingImage];
if (model) {
[photoArray addObject:model];
}
}];
if (completion) {
completion(photoArray);
}
}else if ([result isKindOfClass:[ALAssetsGroup class]]){
ALAssetsGroup *group = (ALAssetsGroup *)result;
if (allowPickingImage && allowPickingVideo) {
[group setAssetsFilter:[ALAssetsFilter allAssets]];
}else if (allowPickingVideo){
[group setAssetsFilter:[ALAssetsFilter allVideos]];
}else if (allowPickingImage){
[group setAssetsFilter:[ALAssetsFilter allPhotos]];
}
ALAssetsGroupEnumerationResultsBlock resultBlock = ^(ALAsset *result, NSUInteger index, BOOL *stop){
if (result == nil) {
if (completion) {
completion(photoArray);
}
}
AssetModel *model = [self assetModelWithAsset:result allowPickingVideo:allowPickingVideo allowPickingImage:allowPickingImage];
if (model) {
[photoArray addObject:model];
}
};
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (resultBlock) {
resultBlock(result,index,stop);
}
}];
}
}
//获取所有图片资源
- (void)getAllAsset:(BOOL)allowPickVideo allowPickImage:(BOOL)allowPickImage completion:(void (^)(NSArray<AssetModel *> *models))completion{
__block NSMutableArray *assetArray = [NSMutableArray array];
[self getAllAlbums:allowPickVideo allowPickingImage:allowPickImage completion:^(NSArray<AlbumModel *> *models) {
for (AlbumModel *model in models) {
[self getAssetsFromFetchResult:model.result allowPickingVideo:allowPickVideo allowPickingImage:allowPickImage completion:^(NSArray<AssetModel *> *models) {
if (models) {
[assetArray addObjectsFromArray:models];
}
}];
}
if (completion) {
completion(assetArray);
}
}];
}
//获取相册的封面图片
- (void)getCoverPhotoWithAlbumModel:(AlbumModel *)model complite:(void (^)(UIImage *photo))complite{
if (iOS8Later) {
id asset = [model.result lastObject];
[self getPhotoWithAsset:asset photoWidth:80 completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
if (complite) {
complite(photo);
}
} progressHandler:^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
}networkAccessAllowed:YES];
}else{
ALAssetsGroup *group = model.result;
UIImage *postImage = [UIImage imageWithCGImage:group.posterImage];
if (complite) {
complite(postImage);
}
}
}
//获取指定的图片
- (PHImageRequestID)getPhotoWithAsset:(id)asset photoWidth:(CGFloat)photoWidth completion:(void (^)(UIImage *photo,NSDictionary *info,BOOL isDegraded))completion progressHandler:(void (^)(double progress, NSError *error, BOOL *stop, NSDictionary *info))progressHandler networkAccessAllowed:(BOOL)networkAccessAllowed{
if ([asset isKindOfClass:[PHAsset class]]) {
CGSize imageSize;
if (!photoWidth || photoWidth <= 50) {
imageSize = CGSizeMake(50, 50);//默认的缩略图的大小
}else{
PHAsset *phAsset = (PHAsset *)asset;
CGFloat aspectRatio = phAsset.pixelWidth / (CGFloat)phAsset.pixelHeight;
CGFloat pixelWidth = photoWidth * 2.0;//2.0代表scale,全部按照@2x显示,因为@3x图片数据太大
CGFloat pixelHeight = pixelWidth / aspectRatio;
imageSize = CGSizeMake(pixelWidth, pixelHeight);
}
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
option.resizeMode = PHImageRequestOptionsResizeModeFast;
PHImageRequestID imageRequestID = [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:imageSize contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
//本地有图片,直接从本地获取
BOOL downloadFinished = (![[info objectForKey:PHImageCancelledKey] boolValue] && ![[info objectForKey:PHImageErrorKey] boolValue]);
if (downloadFinished && result) {
if (completion) {
completion(result,info,[[info objectForKey:PHImageResultIsDegradedKey] boolValue]);
}
}
//压缩图获取失败,获取高清图。如果图片存储在iCloud的话,从云端下载
if ([info objectForKey:PHImageResultIsInCloudKey] && !result && networkAccessAllowed) {
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
if (progressHandler) {
progressHandler(progress, error, stop, info);
}
});
};
options.networkAccessAllowed = YES;
options.resizeMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
UIImage *resultImage = [UIImage imageWithData:imageData scale:0.1];
if (resultImage) {
if (completion) {
completion(resultImage,info,[[info objectForKey:PHImageResultIsDegradedKey] boolValue]);
}
}
}];
}
}];
return imageRequestID;
}else if([asset isKindOfClass:[ALAsset class]]){
ALAsset *alAsset = (ALAsset *)asset;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
CGImageRef thumbImageRef = alAsset.thumbnail;
UIImage *thumbImage = [UIImage imageWithCGImage:thumbImageRef scale:2.0 orientation:UIImageOrientationUp];
dispatch_async(dispatch_get_main_queue(), ^{
if (completion) {
completion(thumbImage,nil,YES);
}
});
});
}
return 0;
}
这里简单的贴出一些方法获取相应的图片资源的方法。
得到这些资源之后,直接展现在coolectionView就可以了。
- (void)timerStart{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
_timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(observeAuthrizationStatusChange) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run];
});
}
- (void)timerStop{
[_timer invalidate];
_timer = nil;
}
- (void)observeAuthrizationStatusChange{
//授权成功
if ([[AlbumImgManager shareManager] autoCheckAuthorizationStatus] == 3) {
//显示imagePicker
NSLog(@"--=======----授权成功");
[self timerStop];
[_albumVC reloadImageData];
}else if([[AlbumImgManager shareManager] autoCheckAuthorizationStatus] != 0){//授权失败
//去显示授权的提示
NSLog(@"--=======----授权失败");
[self timerStop];
}else{
NSLog(@"--=======----授权中,请准备");
}
}
这里添加一个定时器,用来监听用户的授权情况。