我正在关注有关如何从ipad相机捕获条形码扫描仪的教程,这是所编写的代码。该教程是用xcode 8编写的,而我使用的是Xcode10。出现了
错误在do try catch语句中“可选类型'AVCaptureDevice?的值?必须解包到 类型'AVCaptureDevice'的值”
。有人可以告诉我在这种情况下处理可选值的正确方法吗?当我将行更改为“让输入=尝试AVCaptureDeviceInput(device:captureDevice!)”时 该应用程序崩溃。
import AVFoundation
import UIKit
class ScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var video = AVCaptureVideoPreviewLayer() //contains what the camera is pointing at
override func viewDidLoad() {
super.viewDidLoad()
//creates session
let session = AVCaptureSession()
//define capture device
let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
do{
let input = try AVCaptureDeviceInput(device: captureDevice)//Error occurs here
session.addInput(input) //input coming from camera
}
catch{
print("Error")
}
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.code93, AVMetadataObject.ObjectType.code39] //may need to change this based on barcode type
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
session.startRunning()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
答案 0 :(得分:0)
当我搜索此问题的答案时,它仅显示您的问题。然后,我从同事那里寻求帮助,并最终使它顺利运行。尝试下面的代码。
let captureDevice = AVCaptureDevice.default(for: .video)
do{
let input = try AVCaptureDeviceInput(device: captureDevice!)
if self.session.canAddInput(input) {
self.captureSession.addInput(input)
}
}
catch{
print("Error")
}