gpt4 book ai didi

swift - 不能将 Nil 分配给类型 AVCaptureDeviceInput

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:07 25 4
gpt4 key购买 nike

我试过注释掉 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)
}

最佳答案

这对我来说很有意义。如果您想将其设置为零。使用选项。这样你就可以将它设置为零。这是一个很好的机制,可以避免崩溃和大量用于空检查的 if 语句。我推荐的(甚至用于测试)是使用可选项。这就是你的样子:

var deviceInput : AVCaptureDeviceInput?

现在 deviceInput NOT 必须保存任何有效值。所以你可以写下面的(虽然它默认为零)

deviceInput = nil

现在,假设您想在别处使用它。您可以像这样使用if let:

if let myNonNilValue = deviceInput {
// myNonNilValue is for sure not nil
}

关于swift - 不能将 Nil 分配给类型 AVCaptureDeviceInput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33863119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com