创建监听者:[[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
移除监听者:[[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
相册变化的回调,即我们的数据更新变化在这个方法中。
// This callback is invoked on an arbitrary serial queue. If you need this to be handled on a specific queue, you should redispatch appropriately - (void)photoLibraryDidChange:(PHChange *)changeInstance;
获取系统相册:
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];获取用户自定义相册:
PHFetchResult *userAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
获取单个相册:(假设为collection)
[smartAlbum enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) { <span style="white-space:pre"> </span>//在这里我们需要对collection做处理 }];
[userAlums enumerateObjectsUsingBlock:^(PHAssetCollection * _Nonnull collection, NSUInteger idx, BOOL * _Nonnull stop) { <span style="white-space:pre"> </span><pre name="code" class="objc"><span style="white-space:pre"> </span>//在这里我们需要对collection做处理}]; 对collection做处理如下
- (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; }
-(void)getImageByAsset:(PHAsset *)asset makeSize:(CGSize)size makeResizeMode:(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); }]; }