2
votes
let captureDeviceInput: AVCaptureDeviceInput?

    do {
        captureDeviceInput = try AVCaptureDeviceInput(device: device)
        if session.canAddInput(captureDeviceInput) {
            session.addInput(captureDeviceInput)
        }
    
    } 

Getting a compile error:
"Value of optional type 'AVCaptureDeviceInput?' not unwrapped".

Any ways to fix this?

2
captureDeviceInput is optional, you need to unwrap it before you can use it in your canAddInput method. - Marco Pace
Please read the section on Optionals in the Swift book (and the rest of the book too). - rmaddy

2 Answers

0
votes

Any ways to fix this?

Yes. The property is an optional type. You need to unwrap it.

captureDeviceInput = try AVCaptureDeviceInput(device: device)
if let captureDeviceInput = captureDeviceInput
{
    if session.canAddInput(captureDeviceInput) {
            session.addInput(captureDeviceInput)
    }
}
else 
{
    // Do something for a nil result (or nothing, if reasonable)
}
0
votes

Try this:

import Cocoa
import AVFoundation

var captureDeviceInput: AVCaptureDeviceInput!
var device: AVCaptureDevice!
var session: AVCaptureSession!

do {
    captureDeviceInput = try AVCaptureDeviceInput(device: device)
    if ((session?.canAddInput(captureDeviceInput)) != nil) {
        session?.addInput(captureDeviceInput)
    }
}