사용자가 카메라 사용 권한을 부여했는지 확인하는 방법은 무엇입니까?
이것을 쓰려고 :
if usergavepermissiontousercamera
opencamera
else
showmycustompermissionview
이 간단한 작업을 수행하는 현재 방법을 찾을 수 없습니다.
참고 : 다른 방법이 필요한 경우에도 iOS7도 작동해야합니다.
동일한 작업을 수행하기 위해 다음 코드를 사용할 수 있습니다.
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
}
})
}
노트:
AVFoundation
빌드 단계의 이진 링크 섹션에 프레임 워크 를 추가해야합니다.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
}
})
}
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)
}
다음은 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)
}
This will test for the four possible answers, and then either request permission if it is notDetermined
, or direct the user to settings to enable it if it is denied
. If it is restricted
, the current user may not be able to enable it, but you should provide some form of guidance to them.
This will open the camera when permission is given by the user. Otherwise show alert for asking permission.
func openCamera(){
let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
switch (authStatus){
case .notDetermined:
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 .restricted:
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 .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)
}
}
}
after this call this function for showing alert
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)
}
I have modified the above answer and removed the initial prompt, since when we want to use device's camera the system is prompting for permissions itself:
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)
}
You can import the AVFoundation framework and use the authorizationStatus(for:) method shown below and handle the respective cases.
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
}
'Nice programing' 카테고리의 다른 글
Hive SQL에서 현재 날짜를 선택하는 방법 (0) | 2020.12.06 |
---|---|
Node.js-Express를 사용하여 원시 요청 본문 가져 오기 (0) | 2020.12.06 |
환경 변수를 gulp 작업으로 설정하려면 어떻게해야합니까? (0) | 2020.12.06 |
Swift에서 뒤로 스 와이프 제스처 비활성화 (0) | 2020.12.06 |
"Project Navigator"를 클릭하면 Xcode 폴더가 자동으로 확장 됨 (0) | 2020.12.06 |