사용자가 카메라 사용 권한을 부여했는지 확인하는 방법은 무엇입니까?


81

이것을 쓰려고 :

if usergavepermissiontousercamera  
  opencamera
else 
  showmycustompermissionview

이 간단한 작업을 수행하는 현재 방법을 찾을 수 없습니다.
참고 : 다른 방법이 필요한 경우에도 iOS7도 작동해야합니다.


이 링크를 확인해야합니다. stackoverflow.com/questions/25803217/… Swift로 번역하기 어렵지 않아야합니다.
— Mehdi.Sqalli

AVCaptureDevice와 AVAuthorizationStatus는 둘 다 xcode에서 인식하지 못합니다. 아마도 버그 또는 무언가가 될 수 있지만 그렇습니다.
— Esqarrouth 2014

그 대답을 확인했습니다. 자사의 카메라 롤, 카메라가 아니라 그것을 자기
— Esqarrouth

답변:


176

동일한 작업을 수행하기 위해 다음 코드를 사용할 수 있습니다.

if AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) ==  AVAuthorizationStatus.Authorized {
    // Already Authorized
} else {
    AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
       if granted == true {
           // User granted
       } else {
           // User rejected
       }
   })
}

노트:

  1. AVFoundation빌드 단계의 이진 링크 섹션에 프레임 워크 를 추가해야합니다.
  2. import AVFoundation가져 오기를 위해 클래스에 작성해야합니다.AVFoundation

SWIFT 3

if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) ==  AVAuthorizationStatus.authorized {
   // Already Authorized
} else {
   AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
      if granted == true {
         // User granted
      } else {
         // User Rejected
      }
   })
}

스위프트 4

if AVCaptureDevice.authorizationStatus(for: .video) ==  .authorized {
    //already authorized
} else {
    AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
        if granted {
            //access allowed
        } else {
            //access denied
        }
    })
}

감사. 링크 바이너리에 추가하지 않고 가져 오기가 작동했습니다. 하지만 프레임 워크에 재단이 있습니다. 관련이 있습니까?
— Esqarrouth 2014.12.25

1
@Esq : Swift Imports에 따르면 모듈로 액세스 할 수있는 Objective-C 프레임 워크 (또는 C 라이브러리)를 Swift로 직접 가져올 수 있기 때문에 바이너리를 연결할 필요가 없습니다. 여기에는 Foundation, UIKit 및 SpriteKit과 같은 모든 Objective-C 시스템 프레임 워크와 시스템과 함께 제공되는 공통 C 라이브러리가 포함됩니다. Merry X'mas ...
— Midhun MP

고마워요, 당신에게도 메리 크리스마스 :) ios7의 btw이 방법은 요청을받지 못했지만 이미 승인되었습니다. 그 이유는 무엇이며 어떻게 고칠 수 있습니까?
— Esqarrouth 2014

@Esq : 앱에 이미 권한이 있고 설정 앱에 설정된 경우 다시 묻지 않습니다. 권한이 있는지 여부에 관계없이 설정 앱을 확인하십시오.
— Midhun MP

이것을 시도하기 전에 시뮬레이터 설정을 재설정했습니다. 가서 앱에 대한 설정이 없는지 확인했습니다. ios7.1 시뮬레이터에 노력
— Esqarrouth

18

Swift 3.0 업데이트 된 솔루션

func callCamera(){
    let myPickerController = UIImagePickerController()
    myPickerController.delegate = self;
    myPickerController.sourceType = UIImagePickerControllerSourceType.camera

    self.present(myPickerController, animated: true, completion: nil)
    NSLog("Camera");
}
func checkCamera() {
    let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
    switch authStatus {
    case .authorized: callCamera() // Do your stuff here i.e. callCameraMethod()
    case .denied: alertPromptToAllowCameraAccessViaSetting()
    case .notDetermined: alertToEncourageCameraAccessInitially()
    default: alertToEncourageCameraAccessInitially()
    }
}

func alertToEncourageCameraAccessInitially() {
    let alert = UIAlertController(
        title: "IMPORTANT",
        message: "Camera access required for capturing photos!",
        preferredStyle: UIAlertControllerStyle.alert
    )
    alert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
    alert.addAction(UIAlertAction(title: "Allow Camera", style: .cancel, handler: { (alert) -> Void in
        UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
    }))
    present(alert, animated: true, completion: nil)
}

func alertPromptToAllowCameraAccessViaSetting() {

    let alert = UIAlertController(
        title: "IMPORTANT",
        message: "Camera access required for capturing photos!",
        preferredStyle: UIAlertControllerStyle.alert
    )
    alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel) { alert in
        if AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo).count > 0 {
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo) { granted in
                DispatchQueue.main.async() {
                    self.checkCamera() } }
        }
        }
    )
    present(alert, animated: true, completion: nil)
}

나는 당신에게 방법 alertToEncourageCameraAccessInitially 및 alertPromptToAllowCameraAccessViaSetting의 혼합 이름을 생각)
— jonaszmclaren

답을 개선 할 수 있습니다. 좋아질거야. 그렇지 않으면 내가 자유로울 때 그것을 확인할 것입니다. 감사합니다 :) @jonaszmclaren
— Sourabh 샤르마

13

다음은 Swift 4.x 용으로 업데이트 된 정리 된 답변입니다.

iOS 10부터 충돌을 방지하려면 info.plist 파일에서 권한도 요청해야합니다.

여기에 이미지 설명 입력

개인 정보 보호-카메라 사용 설명

이 키와 함께 사용자에게 제공되는 문자열을 제공해야합니다. 그렇게하지 않으면 카메라에 액세스하려고 할 때 충돌이 발생합니다.

import AVFoundation

func checkCameraAccess() {
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    case .denied:
        print("Denied, request permission from settings")
        presentCameraSettings()
    case .restricted:
        print("Restricted, device owner must approve")
    case .authorized:
        print("Authorized, proceed")
    case .notDetermined:
        AVCaptureDevice.requestAccess(for: .video) { success in
            if success {
                print("Permission granted, proceed")
            } else {
                print("Permission denied")
            }
        }
    }
}

func presentCameraSettings() {
    let alertController = UIAlertController(title: "Error",
                                  message: "Camera access is denied",
                                  preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "Cancel", style: .default))
    alertController.addAction(UIAlertAction(title: "Settings", style: .cancel) { _ in
        if let url = URL(string: UIApplicationOpenSettingsURLString) {
            UIApplication.shared.open(url, options: [:], completionHandler: { _ in
                // Handle
            })
        }
    })

    present(alertController, animated: true)
}

네 가지 가능한 답변을 테스트 한 다음 권한이있는 경우 권한을 요청하거나 권한이있는 경우 notDetermined사용자를 설정으로 안내합니다 denied. 인 경우 restricted현재 사용자가 활성화하지 못할 수 있지만 사용자에게 몇 가지 지침을 제공해야합니다.


9

사용자가 권한을 부여하면 카메라가 열립니다. 그렇지 않으면 권한 요청에 대한 경고를 표시합니다.

func openCamera(){
        
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        
        switch (authStatus){
            
        case .notDetermined, .restricted, .denied:
            showAlert(title: "Unable to access the Camera", message: "To enable access, go to Settings > Privacy > Camera and turn on Camera access for this app.")
        case .authorized:
            alert.dismiss(animated: true, completion: nil)
            if(UIImagePickerController .isSourceTypeAvailable(.camera)){
                picker.sourceType = .camera
                picker.showsCameraControls=true
                picker.allowsEditing=true
                self.viewController!.present(picker, animated: true, completion: nil)
            }
        }
}

이 호출 후 경고를 표시하는이 함수

func showAlert(title:String, message:String) {
        let alert = UIAlertController(title: title,
                                      message: message,
                                      preferredStyle: UIAlertController.Style.alert)
        
        let okAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
        alert.addAction(okAction)
        
        let settingsAction = UIAlertAction(title: "Settings", style: .default, handler: { _ in
            // Take the user to Settings app to possibly change permission.
            guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return }
            if UIApplication.shared.canOpenURL(settingsUrl) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                        // Finished opening URL
                    })
                } else {
                    // Fallback on earlier versions
                    UIApplication.shared.openURL(settingsUrl)
                }
            }
        })
        alert.addAction(settingsAction)
        
        self.viewController!.present(alert, animated: true, completion: nil)
    }

+1, 작은 변화 후에 저에게 효과적이었습니다. .notDetermined가 처음 인 경우를 제외하고 모두 좋습니다. .authorised 케이스에서 수행 한 모든 작업을 진행할 수 있습니다. 허용 / 거부를 ​​요청하거나 사용자에게 "AVCaptureDevice.requestAccess (for : .video) ". 다음 시도에서 스위치 케이스는 첫 번째 응답에 따라 따릅니다. 또한 처음으로 거부 / 허용 할 때까지 개인 정보 보호 설정에 표시되지 않습니다.
— Lokesh Purohit 19

2

장치의 카메라를 사용하려고 할 때 시스템 자체에서 권한을 요청하기 때문에 위의 답변을 수정하고 초기 프롬프트를 제거했습니다.

func checkPermissions() {
    let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)

    switch authStatus {
    case .authorized:
        setupCamera()
    case .denied:
        alertPromptToAllowCameraAccessViaSetting()
    default:
        // Not determined fill fall here - after first use, when is't neither authorized, nor denied
        // we try to use camera, because system will ask itself for camera permissions
        setupCamera()
    }
}

func alertPromptToAllowCameraAccessViaSetting() {
    let alert = UIAlertController(title: "Error", message: "Camera access required to...", preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: "Cancel", style: .default))
    alert.addAction(UIAlertAction(title: "Settings", style: .cancel) { (alert) -> Void in
        UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
    })

    present(alert, animated: true)
}

2

AVFoundation 프레임 워크를 가져 와서 아래 표시된 authorizationStatus (for :) 메서드를 사용하고 각 사례를 처리 할 수 ​​있습니다.

switch AVCaptureDevice.authorizationStatus(for: .video) {
    case .authorized: // The user has previously granted access to the camera.
        self.setupCaptureSession()

    case .notDetermined: // The user has not yet been asked for camera access.
        AVCaptureDevice.requestAccess(for: .video) { granted in
            if granted {
                self.setupCaptureSession()
            }
        }

    case .denied: // The user has previously denied access.
        return
    case .restricted: // The user can't grant access due to restrictions.
        return
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.