如何检查用户是否授予使用相机的权限?


81

尝试写这个:

if usergavepermissiontousercamera  
  opencamera
else 
  showmycustompermissionview

找不到执行此简单任务的当前方法。
注意:即使需要其他方法,iOS7也应该可以运行


您应该检查此链接。stackoverflow.com/questions/25803217/…应该不难翻译成Swift。
Mehdi.Sqalli 2014年

xcode可能无法识别AVCaptureDevice和AVAuthorizationStatus,可能是错误或其他东西,但是是的,这使得它很难。
Esqarrouth 2014年

检查了那个答案。其用于相机胶卷,而不是用于相机本身
Esqarrouth 2014年

Answers:


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年

1
@Esq:不需要链接二进制文件,因为根据Swift Imports,任何可以作为模块访问的Objective-C框架(或C库)都可以直接导入到Swift中。这包括所有的Objective-C系统框架(例如Foundation,UIKit和SpriteKit),以及系统随附的通用C库。圣诞快乐...
Midhun MP 2014年

谢谢,也祝您圣诞节快乐:) ios7中的顺便说一句,即使从未收到请求,此方法也会进入已授权的状态。为什么会这样,我该如何解决?
Esqarrouth,2014年

@Esq:如果您的应用已获得许可并在设置应用中进行了设置,则不会再询问。检查您的设置应用是否具有权限。
Midhun MP 2014年

在尝试此操作之前,我重置了模拟器设置。去检查设置没有关于应用程序的地方。在ios7.1模拟器上试用它
Esqarrouth 2014年

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
Sharma

12

以下是为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以外,其他所有情况都将是正确的,因此我们可以继续做在.authorized情况下所做的所有事情,因为它会要求允许/拒绝,或者我们可以向用户显示“ AVCaptureDevice.requestAccess(for : 。视频)”。从下一次尝试开始,切换情况将基于首次响应。同样,在我们第一次拒绝/允许之前,我们不会在隐私设置中看到此信息。
Lokesh Purohit

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
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.