Joe Blow Joe Blow - 2 months ago 15
iOS Question

How to try/catch this type of error in iOS

I have some code

captureSession = AVCaptureSession()
captureSession!.sessionPreset = AVCaptureSessionPresetPhoto
let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) etc...

Of course, this correctly does not work on simulator. No problem.

If you do run it on a simulator, it correctly crashes right here

captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

like this

enter image description here

As a curiosity, how would you "catch" that crash?

If I try to "try" it in different ways,

try captureSession!.sessionPreset = AVCaptureSessionPresetPhoto

I only get...

/Users/jpm/Desktop/development/-/classes/CameraPlane.swift:67:3: No calls to throwing functions occur within 'try' expression

How is it you wrap and catch that type of call?

Just BTW for anyone specifically dealing with this annoyance in the Camera,

func cameraBegin()
captureSession = AVCaptureSession()

if ( AVCaptureDevice.devices().count == 0 )
print("Running on simulator.")


try can only be used when calling a function that throws. These functions are explicitly marked with throws.

If you want to unwrap an optional safely (which I guess is what you want to achieve), you can use guard.

var number: Int?
guard let unwrappedNumber = number else {
print("number: \(unwrappedNumber)")

There is a great example about unwrapping optionals in the documentation.