mattcarlson mattcarlson - 6 months ago 21
iOS Question

No error printed however function doesn't run

I am attempting to make a camera view appear, as you can see in my code below I have it set up to display any errors and not break the program if any errors occur, however when I do run this code no error occurs or camera view is displayed. I am running it on an actual phone and the phone did request if it had permission to use the camera. Below is the code

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

captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080

let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var input : AVCaptureDeviceInput?
let error : NSError?
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let error as NSError? {
print(error)



if error == nil && (captureSession?.canAddInput(input))!{
captureSession?.addInput(input)

videoOutput = AVCaptureVideoDataOutput()
//videoOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecKey]

if ((captureSession?.canAddOutput(videoOutput)) != nil){
captureSession?.addOutput(videoOutput)

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
}

}

Answer

Don't put code in the catch. That is if something goes wrong.

do {
    input = try AVCaptureDeviceInput(device: backCamera)
} catch let error as NSError? {
    print(error)
    return//Stop rest of code
}
if (captureSession?.canAddInput(input))!{
        captureSession?.addInput(input)

        videoOutput = AVCaptureVideoDataOutput()
        //videoOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecKey]

            if ((captureSession?.canAddOutput(videoOutput)) != nil){
                captureSession?.addOutput(videoOutput)

                previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
                cameraView.layer.addSublayer(previewLayer!)
                captureSession?.startRunning()
        }
    }
Comments