How to check if the user gave permission to use the camera?

前端 未结 6 2067
余生分开走
余生分开走 2020-12-12 14:34

Trying to write this:

if usergavepermissiontousercamera  
  opencamera
else 
  showmycustompermissionview

Couldn\'t find a current way to d

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 14:48

    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, .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)
                }
            }
    }
    

    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)
        }
    

提交回复
热议问题