扫描QR码经常崩溃-AVCaptureSession

时间:2018-09-15 13:01:45

标签: ios swift uitabbarcontroller avcapturesession

我正尝试使用以下代码扫描QR码,但效果很好。但是有时它会由于以下错误而崩溃。

无法将类型'AVMetadataFaceObject'(0x1b245bd28)的值强制转换为'AVMetadataMachineReadableCodeObject'(0x1b245be68)。非常感谢。

P.S:正在在标签栏控制器中显示摄像头

func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
    // Check if the metadataObjects array is not nil and it contains at least one object.
    if metadataObjects.count == 0 {
        qrCodeFrameView?.frame = CGRect.zero
        messageLabel.text = "No QR code is detected"
        return
    }
    // Get the metadata object.
    let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
    if supportedCodeTypes.contains(metadataObj.type) {
        // If the found metadata is equal to the QR code metadata (or barcode) then update the status label's text and set the bounds
        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        qrCodeFrameView?.frame = barCodeObject!.bounds
        if metadataObj.stringValue != nil {
            launchApp(decodedURL: metadataObj.stringValue!)
            messageLabel.text = metadataObj.stringValue
            captureSession?.stopRunning()
            captureSession = nil

        }
    }
}

2 个答案:

答案 0 :(得分:3)

强制转换的用例非常有限,这几乎从来不是一个好主意。您应该使用:

guard let metadataObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject else{
    // Display some sort of error message or handle it
    return
}

答案 1 :(得分:1)

确保您检测到QR码且没有面孔:

captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]