PhotoKit 简介
PhotoKit 是iOS8之后新出一套比 AssetsLibrary 更完整也更高效的库,对资源的处理跟 AssetsLibrary 也有很大的不同。
先简单介绍几个Photos的类:
- PHAsset: 代表照片库中的一个资源,跟 ALAsset 类似,通过 PHAsset 可以获取和保存资源
- PHFetchOptions: 获取资源时的参数,可以传 nil,即使用系统默认值
- PHFetchResult: 表示一系列的资源集合,也可以是相册的集合
- PHAssetCollection: 表示一个相册或者一个时刻,或者是一个「智能相册(系统提供的特定的一系列相册,例如:最近删除,视频列表,收藏等等,如下图所示)
- PHImageManager: 用于处理资源的加载,加载图片的过程带有缓存处理,可以通过传入一个 PHImageRequestOptions 控制资源的输出尺寸,同异步获取,是否获取iCloud图片等
- PHCachingImageManager: 继承 PHImageManager ,对Photos的图片或视频资源提供了加载或生成预览缩略图和全尺寸图片的方法,针对预处理巨量的资源进行了优化。
- PHImageRequestOptions: 如上面所说,控制加载图片时的一系列参数
PhotoKit使用
- 导入
#import <Photos/Photos.h>
- 在
Info.plist
添加key:
<key>NSPhotoLibraryUsageDescription</key>
<string>需要访问您的相册,请点击允许</string>
- 如需要系统相册名称跟随系统语言本地化,则在
Info.plist
添加key:
<key>CFBundleAllowMixedLocalizations</key>
<true/>
- 获取相册列表
- (void)fetchAssetCollection
{
PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
// 按创建时间升序
allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
// 获取所有照片(按创建时间升序)
_allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
// 获取所有智能相册
_smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
// 获取所有用户创建相册
_userCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
//_userCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];
}
效果如下:
- 获取具体某个相册的所有
PHAsset
PHFetchResult<PHAsset *> *fetchResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
- 用
PHAsset
请求图片,得到UIImage
对象
cell.representedAssetIdentifier = asset.localIdentifier;
// targetSize 是以像素计量的,所以需要实际的 size * UIScreen.mainScreen.scale
[_imageManager requestImageForAsset:asset targetSize:thumbnailSize contentMode:PHImageContentModeAspectFill options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
// 当 resultHandler 被调用时,cell可能已被回收,所以此处加个判断条件
if ([cell.representedAssetIdentifier isEqualToString:asset.localIdentifier]) {
cell.thumbnailImage = result;
}
}];
此处有人肯定会有疑惑,- (PHImageRequestID)requestImageForAsset:(PHAsset *)asset targetSize:(CGSize)targetSize contentMode:(PHImageContentMode)contentMode options:(nullable PHImageRequestOptions *)options resultHandler:(void (^)(UIImage *__nullable result, NSDictionary *__nullable info))resultHandler
这个方法放在的- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
中执行,不会很卡么?(也许,相册中照片比较少的时候可能感觉不太明显,可以试试超过1000张的滑动效果)当然,如果仅仅是这样,那用户体验太差了。
最重要的核心代码是下面要说的,合理使用PHCachingImageManager
,在滚动一系列缩略图时,我们可以在可视区域前后维护一些数据缓存。借图表达下:
何时执行Start Caching
和Stop Caching
当然得分向上滑动和向下滑动时2种情况各做讨论;
所以需要在的协议方法中根据collectionView.contentOffset.y
判断什么时候Start Caching
和Stop Caching
代码如下:
#pragma mark - UIScrollViewDelegate -
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
[self updateCachedAssets];
}
- (void)updateCachedAssets
{
if (!self.isViewLoaded || self.view.window == nil) {
return;
}
// 预热区域 preheatRect 是 可见区域 visibleRect 的两倍高
CGRect visibleRect = CGRectMake(0.f, self.collectionView.contentOffset.y, self.collectionView.bounds.size.width, self.collectionView.bounds.size.height);
CGRect preheatRect = CGRectInset(visibleRect, 0, -0.5*visibleRect.size.height);
// 只有当可见区域与最后一个预热区域显著不同时才更新
CGFloat delta = fabs(CGRectGetMidY(preheatRect) - CGRectGetMidY(previousPreheatRect));
if (delta > self.view.bounds.size.height / 3.f) {
// 计算开始缓存和停止缓存的区域
[self computeDifferenceBetweenRect:previousPreheatRect andRect:preheatRect removedHandler:^(CGRect removedRect) {
[self imageManagerStopCachingImagesWithRect:removedRect];
} addedHandler:^(CGRect addedRect) {
[self imageManagerStartCachingImagesWithRect:addedRect];
}];
previousPreheatRect = preheatRect;
}
}
计算开始缓存和停止缓存的区域
- (void)computeDifferenceBetweenRect:(CGRect)oldRect andRect:(CGRect)newRect removedHandler:(void (^)(CGRect removedRect))removedHandler addedHandler:(void (^)(CGRect addedRect))addedHandler
{
if (CGRectIntersectsRect(newRect, oldRect)) {
CGFloat oldMaxY = CGRectGetMaxY(oldRect);
CGFloat oldMinY = CGRectGetMinY(oldRect);
CGFloat newMaxY = CGRectGetMaxY(newRect);
CGFloat newMinY = CGRectGetMinY(newRect);
//添加 向下滑动时 newRect 除去与 oldRect 相交部分的区域(即:屏幕外底部的预热区域)
if (newMaxY > oldMaxY) {
CGRect rectToAdd = CGRectMake(newRect.origin.x, oldMaxY, newRect.size.width, (newMaxY - oldMaxY));
addedHandler(rectToAdd);
}
//添加 向上滑动时 newRect 除去与 oldRect 相交部分的区域(即:屏幕外底部的预热区域)
if (oldMinY > newMinY) {
CGRect rectToAdd = CGRectMake(newRect.origin.x, newMinY, newRect.size.width, (oldMinY - newMinY));
addedHandler(rectToAdd);
}
//移除 向上滑动时 oldRect 除去与 newRect 相交部分的区域(即:屏幕外底部的预热区域)
if (newMaxY < oldMaxY) {
CGRect rectToRemove = CGRectMake(newRect.origin.x, newMaxY, newRect.size.width, (oldMaxY - newMaxY));
removedHandler(rectToRemove);
}
//移除 向下滑动时 oldRect 除去与 newRect 相交部分的区域(即:屏幕外顶部的预热区域)
if (oldMinY < newMinY) {
CGRect rectToRemove = CGRectMake(newRect.origin.x, oldMinY, newRect.size.width, (newMinY - oldMinY));
removedHandler(rectToRemove);
}
}
else {
//当 oldRect 与 newRect 没有相交区域时
addedHandler(newRect);
removedHandler(oldRect);
}
}
执行startCachingImagesForAssets
和stopCachingImagesForAssets
- (void)imageManagerStartCachingImagesWithRect:(CGRect)rect
{
NSMutableArray<PHAsset *> *addAssets = [self indexPathsForElementsWithRect:rect];
[_imageManager startCachingImagesForAssets:addAssets targetSize:thumbnailSize contentMode:PHImageContentModeAspectFill options: nil];
}
- (void)imageManagerStopCachingImagesWithRect:(CGRect)rect
{
NSMutableArray<PHAsset *> *removeAssets = [self indexPathsForElementsWithRect:rect];
[_imageManager stopCachingImagesForAssets:removeAssets targetSize:thumbnailSize contentMode:PHImageContentModeAspectFill options:nil];
}
- (NSMutableArray<PHAsset *> *)indexPathsForElementsWithRect:(CGRect)rect
{
UICollectionViewLayout *layout = self.collectionView.collectionViewLayout;
NSArray<__kindof UICollectionViewLayoutAttributes *> *layoutAttributes = [layout layoutAttributesForElementsInRect:rect];
NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
for (__kindof UICollectionViewLayoutAttributes *layoutAttr in layoutAttributes) {
NSIndexPath *indexPath = layoutAttr.indexPath;
PHAsset *asset = [_fetchResult objectAtIndex:indexPath.item];
[assets addObject:asset];
}
return assets;
}
切记:此处执行 startCachingImagesForAssets 和 stopCachingImagesForAssets 时的参数 targetSize,contentMode,options 都要必须和 requestImageForAsset方法里的保持一致
本人手机里有3924张照片,跑了个demo,占用内存最高不超过30M,快速滑动也不会出现掉帧现象。Demo地址SamplePhotosDemo