我无法在UIViewController中访问相机

时间:2018-10-24 08:50:38

标签: ios swift camera ios-permissions

我真的希望我不会重复-但是我在这里阅读了很多不同的相机问题,并实施了所有答案,结果相同:什么也没发生!

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

在这个简单的代码中我怎么了? -还是我需要更改哪个设置?我尝试过使用“数据保护”:什么都没有!

代码:

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的照片(在这里我似乎找不到相机的用法说明)-也许我是个白痴...: enter image description here

谢谢!

2 个答案:

答案 0 :(得分:3)

您需要将camara使用情况描述添加到info.plist文件中,并请求您的应用访问相机的权限。

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

Privacy - Camera Usage Description

带有诸如

之类的文字
  

“我们需要您的许可才能访问设备相机”

请求权限:

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

答案 1 :(得分:0)

运行代码后,必须在UINavigationController中添加 CreateNewPerson

别忘了在info.plist

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