之前項(xiàng)目使用UIImagePickerController獲取相冊。由于iOS 14升級了圖片庫權(quán)限,多了PHAuthorizationStatusLimited權(quán)限。為了適應(yīng)升級,需要用PHPhotoLibrary獲取相冊。
一、 使用PHPickerViewController顯示圖片庫
<PhotosUI/PhotosUI.h>中提供了PHPickerViewController??梢灾苯邮褂茫糜陲@示照片庫。帶原生的搜索功能(很強(qiáng)大)。但是Limited權(quán)限,顯示全部照片而非部分。
@interface PHPickerViewController : UIViewController
/// The delegate to be notified.
@property (NS_NONATOMIC_IOSONLY, weak) id<PHPickerViewControllerDelegate> delegate NS_REFINED_FOR_SWIFT;
/// Initializes new picker with the \c configuration the picker should use.
- (instancetype)initWithConfiguration:(PHPickerConfiguration *)configuration NS_DESIGNATED_INITIALIZER NS_REFINED_FOR_SWIFT;
@end
1.先聲明PHPickerConfiguration
@interface PHPickerConfiguration : NSObject <NSCopying>
//轉(zhuǎn)碼模式
@property (NS_NONATOMIC_IOSONLY) PHPickerConfigurationAssetRepresentationMode preferredAssetRepresentationMode;
//可選擇的照片數(shù)
@property (NS_NONATOMIC_IOSONLY) NSInteger selectionLimit;
//篩選模式設(shè)置,目前可以指定篩選照片、視頻、LivePhoto 幾種類型,或者任何他們的組合。
@property (NS_NONATOMIC_IOSONLY, copy, nullable) PHPickerFilter *filter;
@end
2.使用Delegate獲取照片
@protocol PHPickerViewControllerDelegate <NSObject>
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results;
@end
3.代碼
//跳轉(zhuǎn)代碼
PHPickerConfiguration *config = [[PHPickerConfiguration alloc] initWithPhotoLibrary:[PHPhotoLibrary sharedPhotoLibrary]];
config.filter = [PHPickerFilter imagesFilter];
config.selectionLimit = 1;
self.pickerVC = [[PHPickerViewController alloc] initWithConfiguration:config];
self.pickerVC.delegate = self;
self.pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:self.pickerVC animated:YES completion:^{}];
//代理
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results
{
if (results.count<=0) {//點(diǎn)擊返回
}else{
PHPickerResult *imgResult = [results objectAtIndex:0];//可多選
if ([imgResult.itemProvider canLoadObjectOfClass:UIImage.class]) {
[imgResult.itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(__kindof id<NSItemProviderReading> _Nullable object, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = object;
});
}];
}
}
[self.pickerVC dismissViewControllerAnimated:YES completion:nil];
}
二、使用PHFetchResult獲取圖片
PHFetchResult可以獲取到有限照片庫權(quán)限的照片。如果此時(shí)權(quán)限是全部,則返回全部照片。這種方法只能自己寫UI去顯示。
1.獲取相冊數(shù)據(jù)
1.1PHFetchResult
// Accessing fetched results (fetches objects from the backing store in chunks on demand rather than all at once)
// Fetched objects will be kept in a cache and purged under memory pressure
//訪問獲取的結(jié)果(按需從備份存儲中獲取對象,而不是一次獲取所有對象)
//獲取的對象將保存在緩存中,并在內(nèi)存壓力下清除
PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
其中PHAssetCollection一個(gè)該實(shí)例對象代表一個(gè)相冊。是PHCollection的子類。
typedef NS_ENUM(NSInteger, PHAssetCollectionType) {
PHAssetCollectionTypeAlbum = 1,照片應(yīng)用程序中的相冊 //An album in the Photos app.
PHAssetCollectionTypeSmartAlbum = 2,內(nèi)容動(dòng)態(tài)更新的智能相冊。// A smart album whose contents update dynamically.
PHAssetCollectionTypeMoment API_DEPRECATED("Will be removed in a future release", ios(8, 13), tvos(10, 13)) = 3, // A moment in the Photos app.
}
PHAssetCollectionSubtype
1.User Album Types
// PHAssetCollectionTypeAlbum regular subtypes
PHAssetCollectionSubtypeAlbumRegular = 2, 在iPhone中自己創(chuàng)建的相冊// An album created in the Photos app.
PHAssetCollectionSubtypeAlbumSyncedEvent = 3, 從iPhoto(就是iMac上的圖片app)中導(dǎo)入圖片到設(shè)備//An Event synced to the device from iPhoto.
PHAssetCollectionSubtypeAlbumSyncedFaces = 4, 從圖片app中導(dǎo)入的人物照片// A Faces group synced to the device from iPhoto.
PHAssetCollectionSubtypeAlbumSyncedAlbum = 5, 從圖片app導(dǎo)入的相冊// An album synced to the device from iPhoto.
PHAssetCollectionSubtypeAlbumImported = 6, 從其他的相機(jī)或者存儲設(shè)備導(dǎo)入的相冊// An album imported from a camera or external storage.
2.Cloud Album Types
// PHAssetCollectionTypeAlbum shared subtypes
PHAssetCollectionSubtypeAlbumMyPhotoStream = 100, 用戶的照片流,如果在設(shè)置里關(guān)閉了iCloud開關(guān),就獲取不到了。//The user’s personal iCloud Photo Stream.
PHAssetCollectionSubtypeAlbumCloudShared = 101, iCloud的共享相冊,點(diǎn)擊照片上的共享tab創(chuàng)建后就能拿到了,但是前提是你要在設(shè)置中打開iCloud的共享開關(guān)(打開后才能看見共享tab)// An iCloud Shared Photo Stream.
3.Smart Album Types
// PHAssetCollectionTypeSmartAlbum subtypes
PHAssetCollectionSubtypeSmartAlbumGeneric = 200,一個(gè)沒有更多特定子類型的智能相冊。//A smart album of no more specific subtype.
PHAssetCollectionSubtypeSmartAlbumPanoramas = 201, 一個(gè)智能相冊,將照片庫中的所有全景照片分組。// A smart album that groups all panorama photos in the photo library.
PHAssetCollectionSubtypeSmartAlbumVideos = 202, 將照片庫中的所有視頻資產(chǎn)分組的智能相冊。//A smart album that groups all video assets in the photo library.
PHAssetCollectionSubtypeSmartAlbumFavorites = 203, 標(biāo)記為喜歡、收藏 //A smart album that groups all assets that the user has marked as favorites.
PHAssetCollectionSubtypeSmartAlbumTimelapses = 204, 延時(shí)拍攝、定時(shí)拍攝// A smart album that groups all time-lapse videos in the photo library.
PHAssetCollectionSubtypeSmartAlbumAllHidden = 205, 一個(gè)智能相冊,將照片應(yīng)用程序的“時(shí)刻”視圖中隱藏的所有資產(chǎn)分組。//A smart album that groups all assets hidden from the Moments view in the Photos app.
PHAssetCollectionSubtypeSmartAlbumRecentlyAdded = 206, 最近添加的 //A smart album that groups assets that were recently added to the photo library.
PHAssetCollectionSubtypeSmartAlbumBursts = 207, 連拍//A smart album that groups all burst photo sequences in the photo library.
PHAssetCollectionSubtypeSmartAlbumSlomoVideos = 208, 所有慢鏡頭視頻// A smart album that groups all Slow-Mo videos in the photo library.
PHAssetCollectionSubtypeSmartAlbumUserLibrary = 209, 一個(gè)智能相冊,它將來自用戶自己庫的所有資產(chǎn)(與iCloud共享相冊中的資產(chǎn)不同)。//A smart album that groups all assets that originate in the user’s own library (as opposed to assets from iCloud Shared Albums).
PHAssetCollectionSubtypeSmartAlbumSelfPortraits = 210, 使用前置攝像頭拍攝的作品 //A smart album that groups all photos and videos captured using the device’s front-facing camera.
PHAssetCollectionSubtypeSmartAlbumScreenshots = 211, 屏幕截圖 //A smart album that groups all images captured using the device’s screenshot function.
PHAssetCollectionSubtypeSmartAlbumDepthEffect = 212, 在可兼容的設(shè)備上使用景深模式拍的照片(人像模式) //A smart album that groups all images captured using the Depth Effect camera mode on compatible devices.
PHAssetCollectionSubtypeSmartAlbumLivePhotos = 213, Live Photo資源 //A smart album that groups all Live Photo assets.
PHAssetCollectionSubtypeSmartAlbumAnimated = 214, 將所有圖像動(dòng)畫資源分組的智能相冊。//A smart album that groups all image animation assets.
PHAssetCollectionSubtypeSmartAlbumLongExposures = 215, 啟用長曝光變化的所有Live Photo資源 //A smart album that groups all Live Photo assets where the Long Exposure variation is enabled.
// Used for fetching, if you don't care about the exact subtype
PHAssetCollectionSubtypeAny = NSIntegerMax
2.實(shí)現(xiàn)代碼
2.1獲取所有照片
PHFetchOptions *option = [[PHFetchOptions alloc] init];
//ascending 為YES時(shí),按照照片的創(chuàng)建時(shí)間升序排列;為NO時(shí),則降序排列
option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
self.fetchList = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];//PHFetchResult這個(gè)類型可以當(dāng)成NSArray使用。此時(shí)所有可獲取照片都已拿到,可以刷新UI進(jìn)行顯示
2.2按順序獲取照片顯示
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.synchronous = true;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestImageDataAndOrientationForAsset:[self.fetchList objectAtIndex:indexPath.row] options:options resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, CGImagePropertyOrientation orientation, NSDictionary * _Nullable info)
{
UIImage *image = [UIImage imageWithData:imageData];
}];
參考:
1.照片框架 https://objccn.io/issue-21-4/
2.Photo Frameworks之PHAssetCollection、PHCollectionList和PHAsset http://www.itdecent.cn/p/ac3d7f490f82