獲取相冊權(quán)限
iOS14相冊整理包含 plist設(shè)置么鹤,iOS相冊權(quán)限查詢和調(diào)取處理(兼容iOS14使用PHPickerViewController),以及PHAuthorizationStatusLimited權(quán)限處理秀鞭。
plist 設(shè)置
// NSPhotoLibraryAddUsageDescription 用戶存入相冊時的提示信息解寝。
// NSPhotoLibraryUsageDescription 相冊訪問權(quán)限信息颤介,必須有此項辆毡,不然訪問相冊的時候 APP 會 Crash。
// PHPhotoLibraryPreventAutomaticLimited 如果未適配怪得,App在每次冷啟動時都會觸發(fā)詢問用戶是否需要修改照片權(quán)限咱枉,添加可供App訪問的圖片。
iOS14 權(quán)限查詢
if (@available(iOS 14, *)) {
PHAccessLevel level = PHAccessLevelReadWrite;
PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatusForAccessLevel:level];
switch (status) {
case PHAuthorizationStatusLimited:
NSLog(@"limited");
//權(quán)限處理邏輯看下方
//這里可以直接調(diào)取從新選擇圖片徒恋,也可以直接調(diào)取 [self limtShow];
//建議每次啟動后做一次選擇圖片處理 在調(diào)用[self limtShow]展示
break;
case PHAuthorizationStatusDenied:{
NSLog(@"denied");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"相機(jī)權(quán)限申請" message:@"沒有權(quán)限訪問您的相機(jī)蚕断,您可以進(jìn)入系統(tǒng)“設(shè)置>隱私>相機(jī)”,允許訪問您的相機(jī)" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
[alertView show];
}
break;
case PHAuthorizationStatusAuthorized:
NSLog(@"authorized");
[self takeimagePhoto];
break;
case PHAuthorizationStatusNotDetermined:
NSLog(@"denied");
[self requestAuthorization];
break;
default:
break;
}
} else {
//判斷相冊權(quán)限
PHAuthorizationStatus photoAuthorStatus = [PHPhotoLibrary authorizationStatus];
if (photoAuthorStatus ==PHAuthorizationStatusAuthorized ) {
[self takeimagePhoto];
}else{
[self requestAuthorization];
}
}
請求權(quán)限
-(void)requestAuthorization{
if (@available(iOS 14, *)) {
PHAccessLevel level = PHAccessLevelReadWrite;
// 請求權(quán)限入挣,需注意 limited 權(quán)限盡在 accessLevel 為 readAndWrite 時生效
[PHPhotoLibrary requestAuthorizationForAccessLevel:level handler:^(PHAuthorizationStatus status) {
switch (status) {
case PHAuthorizationStatusLimited:
NSLog(@"limited");
// [self takeimagePhoto];
[self limtShow];
// dispatch_async(dispatch_get_main_queue(), ^{
//
// [[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:[AppUtily currentViewController]];
// });
break;
case PHAuthorizationStatusDenied:
NSLog(@"denied");
[self performSelectorOnMainThread:@selector(doAlert) withObject:nil waitUntilDone:YES];
break;
case PHAuthorizationStatusAuthorized:
NSLog(@"authorized");
[self takeimagePhoto];
break;
default:
break;
}
}];
} else {
//獲取相冊訪問權(quán)限 ios8之后推薦用這種方法 //該方法提示用戶授權(quán)對相冊的訪問
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusDenied) {
NSLog(@"用戶拒絕當(dāng)前應(yīng)用訪問相冊,我們需要提醒用戶打開訪問開關(guān)");
[self performSelectorOnMainThread:@selector(doAlert) withObject:nil waitUntilDone:YES];
}else if (status == PHAuthorizationStatusAuthorized){
//有權(quán)限 可直接跳轉(zhuǎn)
[self takeimagePhoto];
}
}];
}
}
調(diào)取相冊
-(void)takeimagePhoto{
dispatch_async(dispatch_get_main_queue(), ^{
if (@available(iOS 14.0, *)) {
PHPickerConfiguration *configuration = [[PHPickerConfiguration alloc] init];
configuration.filter = [PHPickerFilter imagesFilter]; // 可配置查詢用戶相冊中文件的類型亿乳,支持三種
configuration.selectionLimit = 1; // 默認(rèn)為1,為0時表示可多選径筏。
PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:configuration];
picker.delegate = self;
// picker.editing = YES;//allowsEditing
picker.modalPresentationStyle = UIModalPresentationFullScreen;
picker.view.backgroundColor = [UIColor whiteColor];//注意需要進(jìn)行暗黑模式適配
_picker = picker;
// picker vc葛假,在選完圖片后需要在回調(diào)中手動 dismiss
// [AppUtily currentViewController] 替換成self
[[AppUtily currentViewController] presentViewController:_picker animated:YES completion:^{
}];
//
//
} else {
UIImagePickerController* ipc = [[UIImagePickerController alloc] init];
ipc.navigationBar.translucent = NO;
if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
NSString *requiredMediaType = ( NSString *)kUTTypeImage;
NSArray *arrMediaTypes=[NSArray arrayWithObjects:requiredMediaType,nil];
[ipc setMediaTypes:arrMediaTypes];
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
//ipc.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:ipc.sourceType];
}
// usePhotoImg = YES;
ipc.delegate = self;
ipc.allowsEditing = YES;
ipc.modalPresentationStyle = UIModalPresentationFullScreen;
if (@available(iOS 11, *)) {
UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
}
// [AppUtily currentViewController] 替換成self
[[AppUtily currentViewController] presentViewController:ipc animated:YES completion:nil];
}
});
}
相冊完成回調(diào)
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results API_AVAILABLE(ios(14));{
//結(jié)果為空直接返回
if (!results || !results.count) {
[picker dismissViewControllerAnimated:YES completion:nil];
return;
}
NSItemProvider *itemProvider = results.firstObject.itemProvider;
if ([itemProvider canLoadObjectOfClass:UIImage.class]) {
__weak typeof(self) weakSelf = self;
[itemProvider loadObjectOfClass:UIImage.class completionHandler:^(__kindof id<NSItemProviderReading> _Nullable object, NSError * _Nullable error) {
if ([object isKindOfClass:UIImage.class]) {
__strong typeof(self) strongSelf = weakSelf;
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *image = (UIImage *)object;
//處理獲取的image
if ([strongSelf.delegate respondsToSelector:@selector(TZAlreadyLoginViewDelegateWithActionEnum:withdata:)]) {
[strongSelf.delegate TZAlreadyLoginViewDelegateWithActionEnum:ActionEnumChangeTitleImage withdata:image];
}
[picker dismissViewControllerAnimated:YES completion:nil];
});
}
}];
}
}
iOS14以下UIImagePickerController
#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
//處理獲取的image
if ([self.delegate respondsToSelector:@selector(TZAlreadyLoginViewDelegateWithActionEnum:withdata:)]) {
[self.delegate TZAlreadyLoginViewDelegateWithActionEnum:ActionEnumChangeTitleImage withdata:image];
NSLog(@"tzdelegate---imagePickerController");
}
[picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if ([UIDevice currentDevice].systemVersion.floatValue < 11) {
return;
}
if ([viewController isKindOfClass:NSClassFromString(@"PUPhotoPickerHostViewController")]) {
[viewController.view.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (obj.frame.size.width < 42) {
[viewController.view sendSubviewToBack:obj];
*stop = YES;
}
}];
}
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
if (@available(iOS 11, *)) {
UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
}
iOS14 PHAuthorizationStatusLimited 權(quán)限處理
-(void)limtShow{
PHFetchOptions *option = [[PHFetchOptions alloc] init];
// //ascending 為YES時,按照照片的創(chuàng)建時間升序排列;為NO時匠璧,則降序排列
option.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
self.fetchList = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:option];//PHFetchResult這個類型可以當(dāng)成NSArray使用桐款。此時所有可獲取照片都已拿到,可以刷新UI進(jìn)行顯示
NSMutableArray<PHAsset *> *assets = [NSMutableArray array];
[self.fetchList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
PHAsset *asset = (PHAsset *)obj;
NSLog(@"照片名%@", [asset valueForKey:@"filename"]);
[assets addObject:asset];
}];
NSString * numStr = [NSString stringWithFormat:@"全部圖片(%ld)",assets.count];
self.array_collect = [NSMutableArray array];
NSLog(@"%@",numStr);
for (PHAsset *set in assets) {
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
[[PHImageManager defaultManager] requestImageForAsset:set targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
//設(shè)置處理圖片
[self.array_collect addObject:result];
[self.collection reloadData];
}];
NSLog(@"%lu",(unsigned long)_array_collect.count);
}
}
主動彈出選擇照片PHPickerViewController
[[PHPhotoLibrary sharedPhotoLibrary] presentLimitedLibraryPickerFromViewController:self];
相冊limt 選擇照片后發(fā)生改變
加入?yún)f(xié)議 PHPhotoLibraryChangeObserver //<PHPhotoLibraryChangeObserver>
//在初始化時加入
[[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
//結(jié)束時加入
- (void)dealloc {
[[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
// NSLog(@"%@ dealloc",NSStringFromClass(self.class));
}
- (void)photoLibraryDidChange:(PHChange *)changeInstance;{
[self limtShow];
}