如何检查用户是不是允许使用相机?

Posted

技术标签:

【中文标题】如何检查用户是不是允许使用相机?【英文标题】:How to check if the user gave permission to use the camera?如何检查用户是否允许使用相机? 【发布时间】:2014-12-25 09:52:00 【问题描述】:

试着写这个:

if usergavepermissiontousercamera  
  opencamera
else 
  showmycustompermissionview

找不到当前的方法来完成这个简单的任务。 注意:即使需要不同的方法也应该适用于 ios7

【问题讨论】:

你应该检查这个链接。 ***.com/questions/25803217/… 翻译成 Swift 应该不难。 AVCaptureDevice 和 AVAuthorizationStatus 都无法被 xcode 识别,可能是错误或其他问题,但是是的,这让它变得非常困难。 检查了那个答案。它用于相机胶卷,而不是它自己的相机 【参考方案1】:

您可以使用以下代码来做同样的事情:

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
        
    )

【讨论】:

谢谢。导入工作无需添加到链接二进制文件。但我确实在框架中有基础。有关系吗? @Esq:您不需要链接二进制文件,因为根据 Swift Imports,任何可作为模块访问的 Objective-C 框架(或 C 库)都可以直接导入 Swift。这包括所有的 Objective-C 系统框架——例如 Foundation、UIKit 和 SpriteKit——以及系统提供的通用 C 库。圣诞快乐... 谢谢,也祝你圣诞快乐 :) 顺便说一句,在 ios7 中,此方法进入已经授权,即使它从未收到请求。为什么会这样,我该如何解决? @Esq:如果您的应用已经拥有权限并在设置应用中进行了设置,则不会再次询问。检查您的设置应用程序是否有权限。 我在尝试之前重置了模拟器设置。去检查设置没有关于应用程序的内容。在ios7.1模拟器上试用【参考方案2】:

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 ;)【参考方案3】:

以下是针对 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,当前用户可能无法启用,但您应该为他们提供某种形式的指导。

【讨论】:

【参考方案4】:

这将在用户授予权限时打开相机。否则显示请求许可的警报。

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 : 。视频)”。从下一次尝试切换案例将基于第一次响应。此外,在我们第一次拒绝/允许之前,我们不会在隐私设置中看到这一点。【参考方案5】:

您可以导入 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

【讨论】:

很好的解决方案!!【参考方案6】:

我已经修改了上面的答案并删除了初始提示,因为当我们要使用设备的摄像头时,系统会自行提示权限:

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)

【讨论】:

以上是关于如何检查用户是不是允许使用相机?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 中请求和检查权限

如何检查用户是不是具有特定角色并因此允许某些操作?

如何检查是不是允许用户读取/写入特定注册表项?

Unity3d检查用户是不是拥有授权设备相机

如何使用正则表达式检查用户输入是不是仅包含特殊字符?

检查用户是不是允许应用使用他们的位置