首页 > 解决方案 > 用于条码扫描的快速 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
    }
}

 }

我错过了什么?

标签: swiftxcodeavcapturesession

解决方案


也许你错过了委托方法?在教程中是委托方法:

optional func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection)

解码二维码部分下


推荐阅读