UFO ET IT

사용자가 iOS에서 이미 카메라 액세스를 거부 한 후 사용자에게 카메라 액세스를 요청하는 방법이 있습니까?

ufoet 2020. 12. 30. 08:30
반응형

사용자가 iOS에서 이미 카메라 액세스를 거부 한 후 사용자에게 카메라 액세스를 요청하는 방법이 있습니까?


이 코드를 사용하고 있지만 안타깝게도 작동하지 않습니다.

사용자가 카메라 액세스를 거부 한 후 다음에 카메라를로드하려고 할 때 다시 카메라 사용 권한을 요청하고 싶습니다 (이 경우 카메라보기를 사용하는 바코드 스캐너). 코드에서 다시 요청하더라도 항상 가져 AVAuthorizationStatusDenied오고 granted항상 자동으로 반환 NO합니다.

많은 사용자가 "바코드 스캔을 시도 할 때 화면이 검게 표시됩니다"라고 이메일을 보내고 있는데, 이는 어떤 이유로 카메라 액세스를 거부했기 때문입니다. 거부가 실수 일 가능성이 높기 때문에 다시 메시지를 표시 할 수 있기를 바랍니다.

이 작업을 수행 할 수있는 방법이 있습니까?

    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized)
    {
        NSLog(@"%@", @"You have camera access");
    }
    else if(authStatus == AVAuthorizationStatusDenied)
    {
        NSLog(@"%@", @"Denied camera access");

        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                NSLog(@"Granted access to %@", AVMediaTypeVideo);
            } else {
                NSLog(@"Not granted access to %@", AVMediaTypeVideo);
            }
        }];
    }
    else if(authStatus == AVAuthorizationStatusRestricted)
    {
        NSLog(@"%@", @"Restricted, normally won't happen");
    }
    else if(authStatus == AVAuthorizationStatusNotDetermined)
    {
        NSLog(@"%@", @"Camera access not determined. Ask for permission.");

        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                NSLog(@"Granted access to %@", AVMediaTypeVideo);
            } else {
                NSLog(@"Not granted access to %@", AVMediaTypeVideo);
            }
        }];
    }
    else
    {
        NSLog(@"%@", @"Camera access unknown error.");
    }

몇 가지 조사 끝에 내가 원하는 것을 할 수없는 것 같습니다. 다음은 iOS 8 이상인 경우 대화 상자를 열고 설정 앱을 자동으로 열도록 코딩 한 대안입니다.

몇 가지 참고 사항 :

  • iOS 10부터 NSCameraUsageDescription카메라 액세스를 요청할 수 있도록 Info.plist에 키 를 지정해야합니다 . 그렇지 않으면 앱이 런타임에 충돌합니다.
  • 사용자가 앱에 대한 권한을 변경하면 앱이 종료됩니다. 이에 따라 처리하고 사용자가 "이동"버튼을 누르기 전에 필요한 데이터를 저장하십시오.
  • iOS 8과 11 사이의 어느 시점에서 Apple은 더 이상 사용자가 카메라 설정을 가져 와서 변경하기 위해 설정 앱의 개인 정보 셀을 터치 할 필요가 없습니다. 사용중인 iOS 버전에 따라 사용자가 설정 앱에서 수행해야하는 작업에 대한 지침을 변경할 수 있습니다. 누군가가 변경된 정확한 iOS 버전을 모두 알려주는 댓글을 아래에 남기고 싶다면 멋질 것입니다.

스위프트 4 :

뷰 컨트롤러 상단에서 :

import AVFoundation

카메라보기를 열기 전에 :

@IBAction func goToCamera()
{
    let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    switch (status)
    {
    case .authorized:
        self.popCamera()

    case .notDetermined:
        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (granted) in
            if (granted)
            {
                self.popCamera()
            }
            else
            {
                self.camDenied()
            }
        }

    case .denied:
        self.camDenied()

    case .restricted:
        let alert = UIAlertController(title: "Restricted",
                                      message: "You've been restricted from using the camera on this device. Without camera access this feature won't work. Please contact the device owner so they can give you access.",
                                      preferredStyle: .alert)

        let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }
}

완료 블록이있는 거부 경고 :

func camDenied()
{
    DispatchQueue.main.async
        {
            var alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Close this app.\n\n2. Open the Settings app.\n\n3. Scroll to the bottom and select this app in the list.\n\n4. Turn the Camera on.\n\n5. Open this app and try again."

            var alertButton = "OK"
            var goAction = UIAlertAction(title: alertButton, style: .default, handler: nil)

            if UIApplication.shared.canOpenURL(URL(string: UIApplicationOpenSettingsURLString)!)
            {
                alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Touch the Go button below to open the Settings app.\n\n2. Turn the Camera on.\n\n3. Open this app and try again."

                alertButton = "Go"

                goAction = UIAlertAction(title: alertButton, style: .default, handler: {(alert: UIAlertAction!) -> Void in
                    UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
                })
            }

            let alert = UIAlertController(title: "Error", message: alertText, preferredStyle: .alert)
            alert.addAction(goAction)
            self.present(alert, animated: true, completion: nil)
    }
}

목표 -C :

뷰 컨트롤러 상단에서 :

#import <AVFoundation/AVFoundation.h>

카메라보기를 열기 전에 :

- (IBAction)goToCamera
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized)
    {
        [self popCamera];
    }
    else if(authStatus == AVAuthorizationStatusNotDetermined)
    {
        NSLog(@"%@", @"Camera access not determined. Ask for permission.");

        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted)
        {
            if(granted)
            {
                NSLog(@"Granted access to %@", AVMediaTypeVideo);
                [self popCamera];
            }
            else
            {
                NSLog(@"Not granted access to %@", AVMediaTypeVideo);
                [self camDenied];
            }
        }];
    }
    else if (authStatus == AVAuthorizationStatusRestricted)
    {
        // My own Helper class is used here to pop a dialog in one simple line.
        [Helper popAlertMessageWithTitle:@"Error" alertText:@"You've been restricted from using the camera on this device. Without camera access this feature won't work. Please contact the device owner so they can give you access."];
    }
    else
    {
        [self camDenied];
    }
}

거부 경고 :

- (void)camDenied
{
    NSLog(@"%@", @"Denied camera access");

    NSString *alertText;
    NSString *alertButton;

    BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
    if (canOpenSettings)
    {
        alertText = @"It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Touch the Go button below to open the Settings app.\n\n2. Turn the Camera on.\n\n3. Open this app and try again.";

        alertButton = @"Go";
    }
    else
    {
        alertText = @"It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Close this app.\n\n2. Open the Settings app.\n\n3. Scroll to the bottom and select this app in the list.\n\n4. Turn the Camera on.\n\n5. Open this app and try again.";

        alertButton = @"OK";
    }

    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Error"
                          message:alertText
                          delegate:self
                          cancelButtonTitle:alertButton
                          otherButtonTitles:nil];
    alert.tag = 3491832;
    [alert show];
}

UIAlertView에 대한 위임 호출 :

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3491832)
    {
        BOOL canOpenSettings = (&UIApplicationOpenSettingsURLString != NULL);
        if (canOpenSettings)
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
    }
}

카메라 액세스를 거부하면 사용자는 설정에서 앱에 대한 카메라 사용을 승인 할 수 있습니다. 의도적으로 자신의 코드에서이를 재정의 할 수 없습니다.

다음 샘플 코드를 사용하여이 사례를 감지 한 다음 사용자에게 해결 방법을 설명 할 수 있습니다. iOS 7 UIImagePickerController Camera No Image

NSString *mediaType = AVMediaTypeVideo; // Or AVMediaTypeAudio

AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];

// The user has explicitly denied permission for media capture.
else if(authStatus == AVAuthorizationStatusDenied){
    NSLog(@"Denied");
}

Swift 3.0의 경우

그러면 사용자가 권한을 변경하기위한 설정으로 이동합니다.

func checkCameraAuthorise() -> Bool {
    let status = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
    if status == .restricted || status == .denied {
        let dialog = ZAlertView(title: "", message: "Please allow access to the camera in the device's Settings -> Privacy -> Camera", isOkButtonLeft: false, okButtonText: "OK", cancelButtonText: "Cancel", okButtonHandler:
            { _ -> Void in UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)}, cancelButtonHandler: { alertView in alertView.dismissAlertView() })
        dialog.show()
        return false
    }
    return true
}

카메라 액세스 및 사진 라이브러리 액세스의 전체 코드

import AVFoundation

카메라 동작을 처리하려면 아래 코드를 사용하십시오. 메서드 호출

func openCameraOrLibrary(){
    let imagePicker = UIImagePickerController()
    let alertController : UIAlertController = UIAlertController(title: "Select Camera or Photo Library".localized, message: "", preferredStyle: .actionSheet)
    let cameraAction : UIAlertAction = UIAlertAction(title: "Camera".localized, style: .default, handler: {(cameraAction) in

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) == true {
            if self.isCamAccessDenied() == false { **//Calling cam access method here**
                imagePicker.sourceType = .camera
                imagePicker.delegate = self
                self.present(imagePicker, animated: true, completion: nil)
            }

        }else{
            self.present(self.showAlert(Title: "", Message: "Camera is not available on this Device or accesibility has been revoked!".localized), animated: true, completion: nil)
            self.showTabbar()

        }

    })

    let libraryAction : UIAlertAction = UIAlertAction(title: "Photo Library", style: .default, handler: {(libraryAction) in

        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) == true {

            imagePicker.sourceType = .photoLibrary
            imagePicker.delegate = self
            self.present(imagePicker, animated: true, completion: nil)

        }else{
            self.showTabbar()
            self.present(self.showAlert(Title: "", Message: "Photo Library is not available on this Device or accesibility has been revoked!".localized), animated: true, completion: nil)
        }
    })

    let cancelAction : UIAlertAction = UIAlertAction(title: "Cancel".localized, style: .cancel , handler: {(cancelActn) in
        self.showTabbar()
    })

    alertController.addAction(cameraAction)

    alertController.addAction(libraryAction)

    alertController.addAction(cancelAction)

    alertController.popoverPresentationController?.sourceView = view
    alertController.popoverPresentationController?.sourceRect = view.frame

    self.present(alertController, animated: true, completion: nil)
    self.hideTabbar()

}

카메라 액세스 기능을 처리하는 방법

func isCamAccessDenied()-> Bool
{
    let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
    if status == .restricted || status == .denied {
    DispatchQueue.main.async
        {
            var alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Close this app.\n\n2. Open the Settings app.\n\n3. Scroll to the bottom and select this app in the list.\n\n4. Turn the Camera on.\n\n5. Open this app and try again."

            var alertButton = "OK"
            var goAction = UIAlertAction(title: alertButton, style: .default, handler: nil)

            if UIApplication.shared.canOpenURL(URL(string: UIApplicationOpenSettingsURLString)!)
            {
                alertText = "It looks like your privacy settings are preventing us from accessing your camera to do barcode scanning. You can fix this by doing the following:\n\n1. Touch the Go button below to open the Settings app.\n\n2. Turn the Camera on.\n\n3. Open this app and try again."

                alertButton = "OK"

                goAction = UIAlertAction(title: alertButton, style: .default, handler: {(alert: UIAlertAction!) -> Void in
                    UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!, options: [:], completionHandler: nil)
                })
            }

            let alert = UIAlertController(title: "Error", message: alertText, preferredStyle: .alert)
            alert.addAction(goAction)
            self.present(alert, animated: true, completion: nil)
        }
        return true
    }
    return false
}

참조 URL : https://stackoverflow.com/questions/26070393/is-there-a-way-to-ask-user-for-camera-access-after-they-have-already-denied-it-o

반응형