我已尝试将deviceInput = nil
行注释掉,仅用于测试但遇到其他错误。此代码存在于其他在线示例中,因此我不确定这里发生了什么。
private func captureSetup (position : AVCaptureDevicePosition) {
var captureError : NSError?
var captureDevice : AVCaptureDevice!
for testedDevice in AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo){
if (testedDevice.position == position) {
captureDevice = testedDevice as! AVCaptureDevice
}
}
if (captureDevice == nil) {
captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
}
var deviceInput : AVCaptureDeviceInput
do {
deviceInput = try AVCaptureDeviceInput(device: captureDevice)
} catch let error as NSError {
captureError = error
deviceInput = nil // Nil cannot be assigned to type AVCaptureDeviceInput
if captureError != nil { // new if
print("error: \(captureError?.localizedDescription)")
}
}
captureSession.sessionPreset = AVCaptureSessionPresetHigh
if (captureError == nil) {
if (captureSession.canAddInput(deviceInput)) {
captureSession.addInput(deviceInput)
}
self.videoDataOutput = AVCaptureVideoDataOutput()
self.videoDataOutput!.videoSettings = [kCVPixelBufferPixelFormatTypeKey: Int(kCVPixelFormatType_32BGRA)]
self.videoDataOutput!.alwaysDiscardsLateVideoFrames = true
self.videoDataOutputQueue = dispatch_queue_create("VideoDataOutputQueue", DISPATCH_QUEUE_SERIAL)
self.videoDataOutput!.setSampleBufferDelegate(self, queue: self.videoDataOutputQueue!)
if (captureSession.canAddOutput(self.videoDataOutput)) {
captureSession.addOutput(self.videoDataOutput)
}
}
visageCameraView.frame = UIScreen.mainScreen().bounds
let previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) as AVCaptureVideoPreviewLayer // changed to let
previewLayer.frame = UIScreen.mainScreen().bounds
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
visageCameraView.layer.addSublayer(previewLayer)
}
答案 0 :(得分:10)
这对我来说很有意义。如果你想把它设置为零。使用选项。这样你就可以把它设置为零。这是一个很好的机制来避免崩溃和大量的if语句进行空检查。我推荐的(即使是测试)是使用选项。这就是你的样子:
var deviceInput : AVCaptureDeviceInput?
现在,deviceInput NOT 必须保留任何有效值。所以你可以写下面的内容(虽然它默认为零)
deviceInput = nil
现在,假设您想在其他地方使用它。您可以使用如果让这样:
if let myNonNilValue = deviceInput {
// myNonNilValue is for sure not nil
}