ios 如何检查用户是否允许使用相机?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27646107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if the user gave permission to use the camera?
提问by Esqarrouth
Trying to write this:
试图写这个:
if usergavepermissiontousercamera
opencamera
else
showmycustompermissionview
Couldn't find a current way to do this simple task.
Note: Should also work iOS7 even if it requires a different method
找不到当前的方法来完成这个简单的任务。
注意:即使需要不同的方法,也应该适用于 iOS7
回答by Midhun MP
You can use the following code for doing the same:
您可以使用以下代码执行相同操作:
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
}
})
}
NOTE:
笔记:
- Make sure that you add the
AVFoundation
Framework in the Link Binary section of build phases - You should write
import AVFoundation
on your class for importingAVFoundation
- 确保
AVFoundation
在构建阶段的链接二进制部分添加框架 - 你应该
import AVFoundation
在你的班级上写下导入AVFoundation
SWIFT 3
斯威夫特 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
}
})
}
Swift 4
斯威夫特 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
}
})
}
回答by Sourabh Sharma
Swift 3.0 Updated Solution
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)
}
回答by CodeBender
The following is a cleaned up answer updated for Swift 4.x:
以下是针对 Swift 4.x 更新的清理答案:
Starting with iOS 10, you must also request permission in the info.plist file to avoid a crash:
从 iOS 10 开始,您还必须在 info.plist 文件中请求权限以避免崩溃:
Privacy - Camera Usage Description
隐私 - 相机使用说明
You must provide a string that is presented to the user with this key. Failure to do so will result in a crash when attempting to access the camera.
您必须提供一个字符串,该字符串会通过此密钥呈现给用户。否则将在尝试访问相机时导致崩溃。
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.
这将测试四个可能的答案,然后请求许可(如果是)notDetermined
,或者将用户引导至设置以启用它(如果是)denied
。如果是restricted
,当前用户可能无法启用它,但您应该向他们提供某种形式的指导。
回答by Prashant Sharma
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)
}
回答by Anu Mittal
You can import the AVFoundation framework and use the authorizationStatus(for:)method shown below and handle the respective cases.
您可以导入 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
}
回答by jonaszmclaren
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)
}