用于条形码扫描的swift Avcapture会话无效

时间:2018-05-15 05:46:43

标签: swift xcode avcapturesession

我正在尝试构建条形码扫描仪。我改编了一些tutorial。视频捕获会话正在运行,但它没有检测到任何条形码。我已多次查看代码,仍然无法找到问题所在。这是我检测条形码的代码

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
    }
}

 }

我错过了什么?

1 个答案:

答案 0 :(得分:1)

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

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

解码QR码

部分下的