我无法在 UIViewController 中访问相机

I cannot access the camera in a UIViewController

我真的希望我没有重复 - 但我在这里阅读了很多不同的相机问题并实施了他们的所有答案,结果相同:没有任何反应!

没有错误,应用程序没有崩溃,没有任何问题 - 只是没有相机的迹象,应该被激活!我的目标是在 viewDidAppear 或 viewDidLoad 中激活它,但我也尝试通过将代码连接到按钮来测试它 - 结果相同;没有什么。在我自己的设备和模拟器上:什么都没有!

我在这段简单的代码中犯了什么错误?? - 或者我需要更改哪个设置?我试过 "data protection": nothing!

代码:

class CreateNewPerson: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

func viewDidAppear () {
    let imagePicker = UIImagePickerController()

    imagePicker.delegate = self
    imagePicker.sourceType = .camera
    present(imagePicker, animated: true, completion: nil)
}

private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]!) {
    PersonPhoto.image = info[UIImagePickerControllerOriginalImage] as? UIImage
    dismiss(animated: true, completion: nil)
}

希望有人能帮助我!

info.plist 的照片(我似乎找不到相机使用说明)- 也许我是个白痴...:

谢谢!

您需要在 info.plist 文件中添加 Camara 使用说明,并请求您的应用获得相机访问权限。

将此添加到您的 plist 文件中:

Privacy - Camera Usage Description

带有一些像

这样的文字

"We need your permission to access the device camera"

申请权限:

AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in
    if granted {
        // show the image picker 
    } else {
        // show an error 
    }
}

通常最好检查你是否需要权限或者权限处于什么状态,所以我会这样做...

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated) 

    checkCameraPermissions() 
}

private func checkCameraPermissions() {
    let status = AVCaptureDevice.authorizationStatus(for: .video)
    switch status {
       case .authorized: 
          self.presentPicker()
       case .notDetermined:
           self.requestPermissions()
       case .denied:
          // user denied access
          self.permissionDenied()   
    }
}

private func requestAccess() {
    AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in
        if !granted {
            // show an error 
        }
        // call it again in to recheck now that permissions have changed.
        checkCameraPermissions
    }
}

private func presentPicker() {
    // permissions are all set, continue as planned.
}

private func permissionDenied() {
    // show an alert and link to app settings to turn on

    // usually I would show a view which explains they have denied permission to the camera so this functionality isn't available until they manually change the setting in the app settings.
}

你必须在 UINavigationController 中添加 CreateNewPerson 然后 运行 你的代码。

别忘了在info.plist

中添加隐私-相机使用说明