developer tip

카메라 롤 액세스 권한 요청

optionbox 2020. 11. 29. 10:15
반응형

카메라 롤 액세스 권한 요청


나는 사용자가 '또는 기능 OFF 스위치를 선택할 수 있습니다 어디 설정을 볼 수있는 카메라 롤에 수출 '

사용자가 처음으로 스위치를 켤 때 (첫 번째 사진을 찍을 때가 아니라), 앱에서 카메라 롤에 액세스 할 수있는 권한을 요청하고 싶습니다.

많은 앱에서 동작을 보았지만이를 수행하는 방법을 찾을 수 없습니다.


이 방법에 대한 빌드가 있는지 확실하지 않지만 쉬운 방법은 ALAssetsLibrary를 사용하여 기능을 켤 때 사진 라이브러리에서 의미없는 정보를 가져 오는 것입니다. 그런 다음 가져온 정보를 간단히 무효화하면 사용자에게 사진에 대한 액세스 권한이 표시됩니다.

예를 들어 다음 코드는 카메라 롤의 사진 수를 얻는 것 이상을 수행하지 않지만 권한 프롬프트를 트리거하는 데 충분합니다.

#import <AssetsLibrary/AssetsLibrary.h>

ALAssetsLibrary *lib = [[ALAssetsLibrary alloc] init];
[lib enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
    NSLog(@"%zd", [group numberOfAssets]);
} failureBlock:^(NSError *error) {
    if (error.code == ALAssetsLibraryAccessUserDeniedError) {
        NSLog(@"user denied access, code: %zd", error.code);
    } else {
        NSLog(@"Other error code: %zd", error.code);
    }
}];

편집 : 이 문제를 우연히 발견했습니다. 아래는 사진 앨범에 대한 애플리케이션 액세스 권한 상태를 확인하는 방법입니다.

ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];

if (status != ALAuthorizationStatusAuthorized) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Attention" message:@"Please give this app permission to access your photo library in your settings app!" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
    [alert show];
}

사진 프레임 워크가있는 iOS 8부터 다음을 사용합니다.

스위프트 3.0 :

PHPhotoLibrary.requestAuthorization { status in
    switch status {
    case .authorized:
        <#your code#>
    case .restricted:
        <#your code#>
    case .denied:
        <#your code#>
    default:
        // place for .notDetermined - in this callback status is already determined so should never get here
        break
    }
}

목표 -C :

[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
    switch (status) {
        case PHAuthorizationStatusAuthorized:
            <#your code#>
            break;
        case PHAuthorizationStatusRestricted:
            <#your code#>
            break;
        case PHAuthorizationStatusDenied:
            <#your code#>
            break;
        default:
            break;
    }
}];

문서의 중요 참고 사항 :

이 메서드는 항상 즉시 반환됩니다. 사용자가 이전에 사진 라이브러리 액세스 권한을 부여하거나 거부 한 경우 호출 될 때 처리기 블록을 실행합니다. 그렇지 않으면 경고를 표시하고 사용자가 경고에 응답 한 후에 만 ​​차단을 실행합니다.


iOS 10부터 우리는 거기에서info.plist 설명한 파일에 사진 라이브러리 사용 설명을 제공해야합니다 . 그런 다음이 코드를 사용하여 필요할 때마다 경고를 표시합니다.

- (void)requestAuthorizationWithRedirectionToSettings {
    dispatch_async(dispatch_get_main_queue(), ^{
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        if (status == PHAuthorizationStatusAuthorized)
        {
            //We have permission. Do whatever is needed
        }
        else
        {
            //No permission. Trying to normally request it
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                if (status != PHAuthorizationStatusAuthorized)
                {
                    //User don't give us permission. Showing alert with redirection to settings
                    //Getting description string from info.plist file
                    NSString *accessDescription = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"NSPhotoLibraryUsageDescription"];
                    UIAlertController * alertController = [UIAlertController alertControllerWithTitle:accessDescription message:@"To give permissions tap on 'Change Settings' button" preferredStyle:UIAlertControllerStyleAlert];

                    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
                    [alertController addAction:cancelAction];

                    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Change Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }];
                    [alertController addAction:settingsAction];

                    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
                }
            }];
        }
    });
}

또한 경고가 나타나지 않는 몇 가지 일반적인 경우가 있습니다. 복사를 피하기 위해이 답변을 살펴 보시기 바랍니다 .


사용자가 iOS 6에서 카메라 롤에 처음 쓰기를 시도하면 자동으로 권한을 요청합니다. 추가 코드를 추가 할 필요가 없습니다 (권한 부여 상태가 ALAuthorizationStatusNotDetermined이되기 전에).

사용자가 처음 거부하면 다시 요청할 수 없습니다 (내가 아는 한). 사용자는 설정-> 개인 정보-> 사진 섹션에서 해당 앱별 설정을 수동으로 변경해야합니다.

There is one other option and that is that it the user cannot give permission due other restrictions like parental control, in that case the status is ALAuthorizationStatusRestricted


Swift:

import AssetsLibrary

var status:ALAuthorizationStatus = ALAssetsLibrary.authorizationStatus()

if status != ALAuthorizationStatus.Authorized{
    println("User has not given authorization for the camera roll")
}

#import <AssetsLibrary/AssetsLibrary.h>

//////

ALAuthorizationStatus status = [ALAssetsLibrary authorizationStatus];
    switch (status) {
        case ALAuthorizationStatusRestricted:
        {
            //Tell user access to the photos are restricted
        }

            break;
        case ALAuthorizationStatusDenied:
        {
            // Tell user access has previously been denied
        }

            break;

        case ALAuthorizationStatusNotDetermined:
        case ALAuthorizationStatusAuthorized:

            // Try to show image picker
            myPicker = [[UIImagePickerController alloc] init];
            myPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            myPicker.delegate = self;
            [self presentViewController: myPicker animated:YES completion:NULL];
            break;


        default:
            break;
    }

iOS 9.2.1, Xcode 7.2.1, ARC enabled

'ALAuthorizationStatus' is deprecated: first deprecated in iOS 9.0 - Use PHAuthorizationStatus in the Photos framework instead

Please see this post for an updated solution:

Determine if the access to photo library is set or not - PHPhotoLibrary (iOS 8)

Key notes:

  • Most likely you are designing for iOS7.0+ as of todays date, because of this fact you will need to handle both ALAuthorizationStatus and PHAuthorizationStatus.

The easiest is to do...

if ([PHPhotoLibrary class])
{
   //Use the Photos framework
}
else
{
   //Use the Asset Library framework
}
  • You will need to decide which media collection you want to use as your source, this is dictated by the device that your app. will run on and which version of OS it is using.

  • You might want to direct the user to settings if the authorization is denied by user.

참고URL : https://stackoverflow.com/questions/13572220/ask-permission-to-access-camera-roll

반응형