需求:最近添加图片的快捷提示,当用户点击扩展按钮(“+” 号按钮)时,进行图片快捷提示(类似于微信)
思路:用户点击“+”号按钮时,检索相册中 30s 内最新添加的图片并展示
核心代码:
#import <PhotosUI/PhotosUI.h>
- (void)getRecentlyAddedPhoto:(void (^)(UIImage * _Nullable image, NSDictionary * _Nullable info))resultHandler {
// 获取相册
// 这里的 subtype 可以传其他参数:比方说 PHAssetCollectionSubtypeSmartAlbumScreenshots 截图,这里用的是用户所有的图片资源
PHFetchResult *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
// 获取资源时的参数(与当前时间相差 30s 内的图片)
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.wantsIncrementalChangeDetails = YES;
options.predicate = [NSPredicate predicateWithFormat:@"creationDate > %@", [[NSDate date] dateByAddingTimeInterval:(-30)]];
// sortDescriptors:排序
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
if (collectionResult.count > 0) {
PHFetchResult *fetchResult = [PHAsset fetchAssetsInAssetCollection:[collectionResult firstObject] options:options];
if (fetchResult.count > 0) {
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
// 让 requestImage... 系列的方法变成同步操作
requestOptions.synchronous = YES;
// 获取原图
[[PHImageManager defaultManager] requestImageForAsset:[fetchResult firstObject] targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFit options:requestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (result) {
resultHandler(result, info);
} else {
resultHandler(nil, nil);
}
}];
}
resultHandler(nil, nil);
} else {
resultHandler(nil, nil);
}
}
相关属性
PHAssetCollectionType:
PHAssetCollectionTypeAlbum 相册
PHAssetCollectionTypeSmartAlbum 智能相册
PHAssetCollectionTypeMoment 时刻
PHAssetCollectionSubtype:
常规的子类型
PHAssetCollectionSubtypeAlbumRegular 常规的
PHAssetCollectionSubtypeAlbumSyncedEvent 使用 iTunes 同步操作过来的相册
PHAssetCollectionSubtypeAlbumSyncedFaces 使用 iTuens同步操作过来的人物相册
PHAssetCollectionSubtypeAlbumSyncedAlbum 使用iTunes 同步的所有相册
PHAssetCollectionSubtypeAlbumImported 从外界导入的相册
经分享的子类型
PHAssetCollectionSubtypeAlbumMyPhotoStream 从相册分享得到
PHAssetCollectionSubtypeAlbumCloudShared 从 cloud 分享得到
智能相册子类型
PHAssetCollectionSubtypeSmartAlbumGeneric 通用的
PHAssetCollectionSubtypeSmartAlbumPanoramas 全景
PHAssetCollectionSubtypeSmartAlbumVideos 视屏
PHAssetCollectionSubtypeSmartAlbumFavorites 收藏
PHAssetCollectionSubtypeSmartAlbumTimelapses 延时视屏,也会在PHAssetCollectionSubtypeSmartAlbumVideos在出现
PHAssetCollectionSubtypeSmartAlbumAllHidden 隐藏的
PHAssetCollectionSubtypeSmartAlbumRecentlyAdded 最近添加
PHAssetCollectionSubtypeSmartAlbumBursts 连拍
PHAssetCollectionSubtypeSmartAlbumSlomoVideos Slomo是slow motion的缩写,高速摄影慢动作解析
PHAssetCollectionSubtypeSmartAlbumUserLibrary 用户所有的资源
PHAssetCollectionSubtypeSmartAlbumSelfPortraits 所有前置摄像头拍的照片和视屏
PHAssetCollectionSubtypeSmartAlbumScreenshots 所有的截屏图
不关心子类型时的全部资源
PHAssetCollectionSubtypeAny = NSIntegerMax
相关属性参考自:PhotoKit