GitHub地址:https://github.com/zhuxinleibandou/ZXLChoosePhoto
Photos框架是iOS新引入進來的蜡秽,具體的介紹可以百度一下衷掷,今天這里主要是寫一個照片封裝庫的心得
上干貨~~
引用:http://www.reibang.com/p/42e5d2f75452
照片庫中有兩種資源可供獲取:PHAsset和PHCollection,前者代表圖像或視頻對象审编,后者是前者的集合或自身類型的集合剪决。PHCollection是個基類,有PHAssetCollection和PHCollectionList兩個子類蔗候,分別代表 Photos 里的相冊和文件夾
1.獲取相冊集
- (PHFetchResult *)getAllCollection{
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
return smartAlbums;
}
2.獲取相冊內(nèi)所有照片資源
- (NSMutableArray<PHAsset *> *)getAllAssetInPhotoAblumWithAscending:(BOOL)ascending withCollection:(PHCollection *)collection
{
PHFetchOptions *option = [[PHFetchOptions alloc] init];
//ascending 為YES時怒允,按照照片的創(chuàng)建時間升序排列;為NO時,則降序排列
option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:ascending]];
option.predicate = [NSPredicate predicateWithFormat:@"mediaType == %ld", PHAssetMediaTypeImage];
option.includeAssetSourceTypes = PHAssetSourceTypeUserLibrary; //設(shè)置數(shù)據(jù)源為本地用戶的
NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
BDLog(@"%@",collection.localizedTitle);
if ([collection isKindOfClass:[PHAssetCollection class]]) {
PHAssetCollection *assetCollection = (PHAssetCollection *)collection;
PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:assetCollection options:option];
[result enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
PHAsset *asset = (PHAsset *)obj;
if (!asset.hidden) { //是否被隱藏
NSLog(@"照片名%@", [asset valueForKey:@"filename"]);
[assets addObject:asset];
}
}];
}
return assets;
}
3.解析照片
- (void)accessToImageAccordingToTheAsset:(PHAsset *)asset size:(CGSize)size resizeMode:(PHImageRequestOptionsResizeMode)resizeMode completion:(void(^)(UIImage *image,NSDictionary *info))completion
{
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
//僅顯示縮略圖锈遥,不控制質(zhì)量顯示
/**
PHImageRequestOptionsResizeModeNone,
PHImageRequestOptionsResizeModeFast, //根據(jù)傳入的size纫事,迅速加載大小相匹配(略大于或略小于)的圖像
PHImageRequestOptionsResizeModeExact //精確的加載與傳入size相匹配的圖像
*/
option.resizeMode = resizeMode;
option.networkAccessAllowed = false; //不允許網(wǎng)絡(luò)請求,icold圖片請求不到
//param:targetSize 即你想要的圖片尺寸所灸,若想要原尺寸則可輸入PHImageManagerMaximumSize
//解析縮略圖
[[PHCachingImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
//解析出來的圖片
completion(image,info);
}];
}