swift - 用于条码扫描的快速 Avcapture 会话不起作用
问题描述
我正在尝试构建条形码扫描仪。我改编了本 教程的一些内容。视频捕获会话正在运行,但未检测到任何条形码。我已经多次查看代码,但仍然找不到问题所在。这是我检测条形码的代码
class ScanController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var qrCodeFrameView: UIView?
let supportedCodeTypes = [AVMetadataObject.ObjectType.upce,
AVMetadataObject.ObjectType.code39,
AVMetadataObject.ObjectType.qr]
override func viewDidLoad() {
super.viewDidLoad()
//Get an instance of the AVCaptureDevice class a device object and provide the video as the media type parameter
let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
do {
// Get an instance of the AVCaptureDeviceInput class using the previous device object.
let input = try AVCaptureDeviceInput(device: captureDevice!)
// Initialize the captureSession object.
captureSession = AVCaptureSession()
// Set the input device on the capture session.
captureSession?.addInput(input)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
// Set delegate and use the default dispatch queue to execute the call back
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = supportedCodeTypes
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
// Start video capture.
captureSession?.startRunning()
// Add the message label
self.view.addSubview(messageLabel)
//initialize QR Code Frame to highlight the QR Code
qrCodeFrameView = UIView()
if let qrCodeFrameView = qrCodeFrameView {
qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
qrCodeFrameView.layer.borderWidth = 2
view.addSubview(qrCodeFrameView)
view.bringSubview(toFront: qrCodeFrameView)
}
} catch {
// If any error occurs, simply print it out and don't continue any more.
print("THERE IS A PROBLEM WITH THE CAPTURE SESSION *****************")
print(error)
return
}
}
}
我错过了什么?
解决方案
也许你错过了委托方法?在教程中是委托方法:
optional func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection)
在解码二维码部分下
推荐阅读
- swift - 属性初始化程序在“自我”可用之前运行错误
- python - 在我的代码中找到具有最高值的 for 循环中的迭代
- node.js - 如何让 React 应用程序的 npm run build 包含我的环境变量?
- artificial-intelligence - 不支持语言的聊天机器人
- javascript - .append 有实用的替代方案吗?
- ember.js - 我如何将作为数组传递的类属性设置为内部渲染组件以进行 ember 测试,因为目前使用 set doesnt pass array?
- rust - 如何将 time::SteadyTime 对象作为 f64 获取?
- java - 检查是否通过 Bash 安装 Java 不起作用
- angular - Angular 中的脚本和使用 A-Frame 的打字稿的问题
- c - 使用“--target=x86_64-pc-windows-gnu”时,Rust Cargo Staticlibrary 构建失败