【问题标题】:Nil cannot be assigned to type AVCaptureDeviceInputNil 不能分配给类型 AVCaptureDeviceInput
【发布时间】:2015-11-23 03:00:48
【问题描述】:

我已尝试将 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)
}

【问题讨论】:

    标签: swift


    【解决方案1】:

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

    var deviceInput : AVCaptureDeviceInput?
    

    现在 deviceInput 确实 必须保存任何有效值。因此您可以编写以下内容(尽管默认为 nil)

    deviceInput = nil
    

    现在,假设您想在其他地方使用它。你可以像这样使用 if let

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 2021-07-02
      • 1970-01-01
      • 2022-01-27
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      相关资源
      最近更新 更多