iOS 14適配相冊權限

? ? ?最近需要適配iOS 14的相冊權限,在網上查了很多資料,大部分資料都只講一部分缺另一部分,想把整個相冊權限適配好還是有點麻煩,現在辦把我整個適配過程記錄下來,需要適配的兄弟可以參考一下

? ? ?在 iOS13 及以前,當用戶首次訪問應用程序時,會被要求開放大量權限,比如相冊、定位、聯系人,實際上該應用可能僅僅需要一個選擇圖片功能,卻被要求開放整個照片庫的權限,這確實是不合理的。對于相冊,在 iOS14 中引入了 “LimitedPhotos Library” 的概念,用戶可以授予應用訪問其一部分的照片,對于應用來說,僅能讀取到用戶選擇讓應用來讀取的照片,讓我們看到了 Apple 對于用戶隱私的尊重。這僅僅是一部分,在iOS14 中,可以看到諸多類似的保護用戶隱私的措施,也需要我們升級適配。?

? ? ? iOS14 新增了“Limited Photo Library Access” 模式,在授權彈窗中增加了 Select Photo 選項。用戶可以在 App 請求調用相冊時選擇部分照片讓 App 讀取。從 App 的視?來看,你的相冊里就只有這幾張照片,App 無法得知其它照片的存在。


? ?當一下次在進入時有會彈提示框,讓你選擇更多圖片或者保留當前選擇,這個提示框不太友好,可以在plist文件里面通過設置?Prevent limited photos access alert = YES隱藏提示


當選擇添加更多圖片是,可以通過? ? [[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:self];到相冊添加刪除圖片,然后監聽圖片變化做相應處理。

對于PHAuthorizationStatusLimited權限的適配,我采用的方案是,先繪制一個列表用于顯示授權的圖片,圖片的資源也就是授權訪問的,當要添加更多圖片是通過?[[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:self];跳轉到相冊,添加圖片,添加完成后監聽圖片變化,更新列表,下面是我的代碼:

?if (@available(iOS 14.0, *)) {

? ? ? ? ? ? PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite];

? ? ? ? ? ? ? switch(status) {

? ? ? ? ? ? ? ? ? case PHAuthorizationStatusNotDetermined:

? ? ? ? ? ? ? ? ? ? ? [self dispatchAuthorizationForAccessLevel];

? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? case PHAuthorizationStatusLimited:

? ? ? ? ? ? ? ? ? ? ? NSLog(@"limited");

? ? ? ? ? ? ? ? ? ? ? [selfe_enterGDPickerVC];

? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? ? // 用戶拒絕當前應用訪問相冊

? ? ? ? ? ? ? ? ? case PHAuthorizationStatusDenied:

? ? ? ? ? ? ? ? ? ? ? NSLog(@"denied");

? ? ? ? ? ? ? ? ? ? ? [self disptachPHAuthorizationStatusDenied];

? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? ? // 用戶允許當前應用訪問相冊

? ? ? ? ? ? ? ? ? case PHAuthorizationStatusAuthorized:

? ? ? ? ? ? ? ? ? ? ? NSLog(@"authorized");

? ? ? ? ? ? ? ? ? ? ? [self P_enterPHPickerViewController];

? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? default:

? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? }

? ? ? ? }

/用戶第一次訪問

-(void)dispatchAuthorizationForAccessLevel{

? ? [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) {

? ? ? ? ? ? ? ? switch(status) {

? ? ? ? ? ? ? ? ? ? case PHAuthorizationStatusLimited:

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{

? ? ? ? ? ? ? ? ? ? ? ? ? ? [selfe_enterGDPickerVC];

? ? ? ? ? ? ? ? ? ? ? ? });

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? case PHAuthorizationStatusDenied:

? ? ? ? ? ? ? ? ? ? {

? ? ? ? ? ? ? ? ? ? ? ? NSLog(@"denied");

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? case PHAuthorizationStatusAuthorized:

? ? ? ? ? ? ? ? ? ? {


? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? ? ? default:

? ? ? ? ? ? ? ? ? ? ? ? break;

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }];


}

//進入授權訪問的圖片控制器

-(void)e_enterGDPickerVC{

? ? MJWeakSelf;

? ? GDPickerVC *picker = [GDPickerVC new];

? ? picker.currentImageContent= ^(UIImage*_NonnullimageContent) {

? ? ? ? NSLog(@"--選擇圖片--");

? ? ? ? if(!imageContent) {

? ? ? ? ? ? return;

? ? ? ? }

? ? ? ? [weakSelfanalysisImageWithContent:imageContent];

? ? };

? ? UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:picker];

? ? nv.modalPresentationStyle? =0;

? ? [_controller presentViewController:nv animated:YES completion:nil];

}


----------授權圖片列表--------------

//

//

#import "GDPickerVC.h"

#import

#import "GDPickerCollectionViewCell.h"

#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)

// 屏幕高度,會根據橫豎屏的變化而變化

#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)

@interface GDPickerVC ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property (nonatomic, strong) UICollectionView *collectionView;

@property (nonatomic, strong) NSMutableArray *photoArray;

@end

@implementation GDPickerVC

- (void)viewDidLoad {

? ? [super viewDidLoad];

? ? self.view.backgroundColor = [UIColor whiteColor];


? ? self.title = @"顯示允許訪問的圖片";

? ? //左邊返回按鈕

? ? UIButton *fanHuiButton = [UIButton buttonWithType:UIButtonTypeCustom];

? ? fanHuiButton.frame=CGRectMake(0,0,30,40);

? ? [fanHuiButtonsetTitle:@"取消"forState:0];

? ? [fanHuiButtonsetTitleColor:[UIColor systemBlueColor] forState:0];

? ? [fanHuiButtonaddTarget:self action:@selector(comebackFuncation) forControlEvents:UIControlEventTouchUpInside];

? ? UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:fanHuiButton];

? ? self.navigationItem.leftBarButtonItem = leftItem;


? ? UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];

? ? rightButton.frame=CGRectMake(0,0,30,40);

? ? [rightButtonsetTitle:@"添加"forState:0];

? ? [rightButtonsetTitleColor:[UIColor systemBlueColor] forState:0];

? ? [rightButtonaddTarget:self action:@selector(confirmButton:) forControlEvents:UIControlEventTouchUpInside];

? ? UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];

? ? self.navigationItem.rightBarButtonItem = rightItem;


? ? //獲取圖片

? ? [self getLibarayPhotoImage];

? ? self.photoArray = [NSMutableArray array];

? ? [self.view addSubview:self.collectionView];


}

#pragma mark - UICollectionViewDataSource

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

? ? return CGSizeMake(SCREEN_WIDTH/3-2,SCREEN_WIDTH/3);

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

? ? return self.photoArray.count;

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

? ? UIImage*image =self.photoArray[indexPath.row];

? ? GDPickerCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(GDPickerCollectionViewCell.class) forIndexPath:indexPath];

? ? cell.imgView.image= image;

? ? returncell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{


? ? UIImage*image =self.photoArray[indexPath.row];

? ? if (_currentImageContent&&image) {

? ? ? ? _currentImageContent(image);

? ? ? ? [self comebackFuncation];

? ? }

}

#pragma response

//返回

-(void)comebackFuncation{

? ? [self dismissViewControllerAnimated:YES completion:nil];

}

//點擊確認回調數據

-(void)confirmButton:(UIButton *)btn{

? ? [[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:self];

? ? [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];

}

- (void)photoLibraryDidChange:(PHChange *)changeInstance

{

? ? [self.photoArray removeAllObjects];

? ? [self getLibarayPhotoImage];

}

/*? 遍歷相簿中的全部圖片

*? @param assetCollection 相簿

*? @param original? ? ? ? 是否要原圖

*/

-(void)getLibarayPhotoImage01{

? ? __weaktypeof(self) weakSelf =self;

? ? NSMutableArray<UIImage *> *images = [NSMutableArray array];

? ? //獲取可訪問的圖片配置選項

? ? PHFetchOptions *option = [[PHFetchOptions alloc] init];

? ? //根據圖片的創建時間升序排序返回

? ? option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

? ? //獲取類型為image的資源

? ? PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];

?? ? //遍歷出每個PHAsset資源對象

? ? [resultenumerateObjectsUsingBlock:^(id? _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

? ? ? ? PHAsset*asset = (PHAsset*)obj;

? ? ? ? //將PHAsset解析為image的配置選項

? ? ? ? PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];

? ? ? ? //圖像縮放模式

? ? ? ? requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;

? ? ? ? //圖片質量

? ? ? ? requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;

? ? ? ? //PHImageManager解析圖片

? ? ? ? [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:requestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

? ? ? ? ? ? NSLog(@"圖片 %@",result);

? ? ? ? ? ? //在這里可以自定義一個顯示可訪問相冊資源的viewController.

? ? ? ? ? ? if(result) {

? ? ? ? ? ? ? ? [weakSelf.photoArrayaddObject:result];

? ? ? ? ? ? }

? ? ? ? }];

? ? ? ? dispatch_async(dispatch_get_main_queue(), ^{

? ? ? ? ? ? [self.collectionView reloadData];

? ? ? ? });

? ? }];


}

-(void)getLibarayPhotoImage{


? ? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

? ? ? ? PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

? ? ? ? for(PHAssetCollection*assetCollectioninassetCollections) {

? ? ? ? ? ? [self enumerateAssetsInAssetCollection:assetCollection original:YES];

? ? ? ? }


? ? ? ? PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;

? ? ? ? [self enumerateAssetsInAssetCollection:cameraRoll original:YES];

? ? });


}

- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollectionoriginal:(BOOL)original

{

?? PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];

?? options.resizeMode = PHImageRequestOptionsResizeModeFast;

?? options.synchronous=YES;

?? PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];

?? for(PHAsset*assetinassets) {

?? ? ? CGSize size = original ? CGSizeMake(asset.pixelWidth, asset.pixelHeight) : CGSizeZero;

?? ? ? __weaktypeof(self) weakSelf =self;

?? ? ? [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:options resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {

?? ? ? ? ? NSLog(@"%@", result);

?? ? ? ? ? if(result) {

?? ? ? ? ? ? ? original ? [weakSelf.photoArrayaddObject:result] : [weakSelf.photoArrayaddObject:result];

?? ? ? ? ? }

?? ? ? }];

?? ? ? dispatch_async(dispatch_get_main_queue(), ^{

?? ? ? ? ? [weakSelf.collectionViewreloadData];

?? ? ? });

?? }

}

#pragma mark--懶加載

- (UICollectionView *)collectionView{

? ? if (!_collectionView) {

? ? ? ? UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];

? ? ? ? flowLayout.minimumLineSpacing=2;

? ? ? ? flowLayout.minimumInteritemSpacing = 1;

? ? ? ? UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];

? ? ? ? collectionView.backgroundColor = self.view.backgroundColor;

? ? ? ? collectionView.delegate=self;

? ? ? ? collectionView.dataSource=self;

? ? ? ? [collectionViewregisterClass:GDPickerCollectionViewCell.class forCellWithReuseIdentifier:NSStringFromClass(GDPickerCollectionViewCell.class)];

? ? ? ? _collectionView= collectionView;

? ? }

? ? return _collectionView;

}

@end

上面是PHAuthorizationStatusLimited 用戶已授權此應用程序進行有限照片庫訪問(iOS14新增)的適配,下面在來說一下適配允許訪問所有圖片,下面是適配代碼

//ios14后使用

-(void)P_enterPHPickerViewController{

? ? MJWeakSelf;

? ? //用戶選擇"允許訪問所有照片",調用PHPickerViewController顯示圖片選擇器

? ? dispatch_async(dispatch_get_main_queue(), ^{

? ? ? ? PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];

? ? ? ? //只獲取image類型資源

? ? ? ? configuration.filter = [PHPickerFilter imagesFilter];

?? ? ? ? //可以多選

//? ? ? ? configuration.selectionLimit = 1;

? ? ? ? PHPickerViewController *pickerVC = [[PHPickerViewController alloc] initWithConfiguration:configuration];

? ? ? ? pickerVC.delegate=self;

? ? ? ? pickerVC.modalPresentationStyle = UIModalPresentationFullScreen;

? ? ? ? [weakSelf.controller presentViewController:pickerVC animated:YES completion:^{

? ? ? ? }];

? ? });

}


- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results

{

? ? MJWeakSelf;

? ? [pickerdismissViewControllerAnimated:YES completion:nil];

? ? if(!results || !results.count) {

? ? ? ? return;

? ? }

? ? NSLog(@"didFinishPicking");

? ? NSItemProvider *itemProvider = results.firstObject.itemProvider;

?? ? ? ? if ([itemProvider canLoadObjectOfClass:UIImage.class]) {

?? ? ? ? ? ? __weaktypeof(self) weakSelf =self;

?? ? ? ? ? ? [itemProviderloadObjectOfClass:UIImage.class completionHandler:^(__kindof id<NSItemProviderReading>? _Nullable object, NSError * _Nullable error) {

?? ? ? ? ? ? ? ? if([objectisKindOfClass:UIImage.class]) {

?? ? ? ? ? ? ? ? ? ? UIImage*image = (UIImage*)object;

?? ? ? ? ? ? ? ? ? ? [weakSelfanalysisImageWithContent:image];

?? ? ? ? ? ? ? ? }

?? ? ? ? ? ? }];

?? ? ? ? }

}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
禁止轉載,如需轉載請通過簡信或評論聯系作者。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,882評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,208評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,746評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,666評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,477評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,960評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,047評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,200評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,726評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,617評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,807評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,327評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,049評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,425評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,674評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,432評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,769評論 2 372

推薦閱讀更多精彩內容