Search code examples
iosswiftxcode11

unexpectedly found nil while unwrapping an optional value. avcapturedeviceinput


class ViewController: UIViewController {

    @IBOutlet weak var cameraView: UIView!

    var captureSession: AVCaptureSession?
    var videoPreviewLayer: AVCaptureVideoPreviewLayer?
    var frontCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for :.video, position: .front)
    var backCamera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)


    override func viewDidLoad() {
        super.viewDidLoad()

        if #available(iOS 10.2, *){

            let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
            do{
                let input = try AVCaptureDeviceInput(device: captureDevice!)
                captureSession = AVCaptureSession()
                captureSession?.addInput(input)
                videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
                videoPreviewLayer?.frame = view.layer.bounds
                cameraView.layer.addSublayer(videoPreviewLayer!)
                captureSession?.startRunning()
            }
            catch {
                print("error")
            }
        }
        // Do any additional setup after loading the view.
    }

    @IBAction func ImageCapture(_ sender: Any) {

    }

I am coding a simple camera app on swift code. I tried in 2 different ways but I get the same error in both.

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

here

let input = try AVCaptureDeviceInput(device: captureDevice!)

How could I fix it?


Solution

  • Are you running it in the simulator? Coz it won't work. It will work in a real device. Also safely unwrap your captureDevice using if let statement. This wont crash the app.

    if #available(iOS 10.2, *){
    
        if let captureDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) {
            do{
                let input = try AVCaptureDeviceInput(device: captureDevice)
                captureSession = AVCaptureSession()
                captureSession?.addInput(input)
                videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
                videoPreviewLayer?.frame = view.layer.bounds
                cameraView.layer.addSublayer(videoPreviewLayer!)
                captureSession?.startRunning()
            }
            catch {
                print("error")
            }
        } else {
            print("camera not available")
        }
    }