我正在尝试获取捕获设备的图像,但它仍然按if let input...
返回nil,我无法找到解决方案。
它试图捕获错误,但它立即兑现..
let backCamera = AVCaptureDevice.default(for: AVMediaType.video)
do {
if let input = try AVCaptureDeviceInput(device: backCamera!) as? AVCaptureInput {
if (captureSession?.canAddInput(input))! {
captureSession?.addInput(input)
stillImageOutput = AVCapturePhotoOutput()
let settings = AVCapturePhotoSettings()
let settingsFormat = [AVVideoCodecKey : AVVideoCodecType.jpeg]
settings.previewPhotoFormat = settingsFormat
stillImageOutput?.capturePhoto(with: settings, delegate: self as! AVCapturePhotoCaptureDelegate)
if (captureSession?.canAddOutput(stillImageOutput!))! {
captureSession?.addOutput(stillImageOutput!)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
previewLayer?.videoGravity = AVLayerVideoGravity.resizeAspect
previewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
}
} catch let error as NSError {
print("Error: \(error)")
}
答案 0 :(得分:1)
这不是你的错误导致崩溃 - 它是你所有的力量解开。 backCamera
,captureSession
,stillImageOutput
和previewLayer
都是Optional
,但您每次都会强制展开所有这些内容。为什么不使用保护语句或可选绑定来避免那些崩溃?最终,如果这些项目为零,您无法运行任何代码,因此我会像这样重构您的代码:
//Use guard to make sure you have a non-nil captureSession and a default device for .video
guard let captureSession = captureSession, let backCamera = AVCaptureDevice.default(for: AVMediaType.video) else { return }
do {
if let input = try AVCaptureDeviceInput(device: backCamera) as? AVCaptureInput {
if (captureSession.canAddInput(input)) {
captureSession.addInput(input)
stillImageOutput = AVCapturePhotoOutput()
//Since stillImageOutput is an Optional I'm putting in another guard just to avoid having to deal with it as an Optional
guard let stillImageOutput = stillImageOutput else { return }
let settings = AVCapturePhotoSettings()
let settingsFormat = [AVVideoCodecKey : AVVideoCodecType.jpeg]
settings.previewPhotoFormat = settingsFormat
stillImageOutput.capturePhoto(with: settings, delegate: self as! AVCapturePhotoCaptureDelegate)
if (captureSession.canAddOutput(stillImageOutput)) {
captureSession.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
//Same as above - since you declared previewLayer as Optional I'll guard so I don't have to deal with it as an Optional
guard let previewLayer = previewLayer else { return }
previewLayer.videoGravity = AVLayerVideoGravity.resizeAspect
previewLayer.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer)
captureSession.startRunning()
}
}
}
} catch let error {
print("Error: \(error)")
}
老实说,其中一些有点矫枉过正,所以它有点个人偏好,但有AVCaptureDevice.default...
这样的地方,根据你的实际设备,它真的可能是也可能不是如果它不存在,可能不要想让它崩溃。