2
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?

Community
  • 1
  • 1
tchen2
  • 61
  • 4
  • `captureDeviceInput` is optional, you need to unwrap it before you can use it in your `canAddInput` method. – Marco Pace Nov 28 '17 at 15:28
  • 1
    Please read the section on [Optionals](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID309) in the Swift book (and the rest of the book too). – rmaddy Nov 28 '17 at 15:31

2 Answers2

0

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)
}
JeremyP
  • 84,577
  • 15
  • 123
  • 161
0

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)
    }
}
Andy Jazz
  • 49,178
  • 17
  • 136
  • 220