简体   繁体   English

如何在AVcapture会话中启动动作

[英]How to initiate an action in AVcapture Session

I wrote a code for scanning barcodes. 我写了一个用于扫描条形码的代码。 I want to display a view when a barcode has been scanned. 我想在扫描条形码后显示视图。 This is my barcode scanner code 这是我的条形码扫描仪代码

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {

    // Check if the metadataObjects array is not nil and it contains at least one object.
    if metadataObjects == nil || metadataObjects.count == 0 {
        qrCodeFrameView?.frame = CGRect.zero
        messageLabel.text = "No QR/barcode is detected"
        return
    }
    //Get metadata object
    let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
    if supportedCodeTypes.contains(metadataObj.type) {
        //if the found metadata is equal to the QR code metadata then update the status label's text and set the the bounds
        let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
        qrCodeFrameView?.frame = barCodeObject!.bounds

        if metadataObj.stringValue != nil {
            var productbarcode = metadataObj.stringValue
            messageLabel.text = productbarcode
            print("Barcode detected")

        }
    }
}

The view I want to display is setup in func Setupproductcontainer() . 我要显示的视图是在func Setupproductcontainer() It works fine when I add it to viewDidLoad but I don't want it to display until a barcode is detected. 当我将其添加到viewDidLoad时,它可以正常工作,但是我不希望它在检测到条形码之前显示。 So I tried adding Setupproductcontainer() under the print("Barcode detected") statement but nothing happens. 因此,我尝试在print("Barcode detected")语句下添加Setupproductcontainer() ,但没有任何反应。 how can I initiate the Setupproductcontainer() when the barcode is detected? 检测到条形码后如何启动Setupproductcontainer()

It's possible that you are trying to make a UI change on a background thread. 您可能正在尝试在后台线程上更改UI。

I suggest you call your function inside a DispatchQueue.main code block to run it on the main thread. 我建议您在DispatchQueue.main代码块内调用函数以在主线程上运行它。 The reason you should do this is every change made on the UI should be done in the main thread. 您应该执行此操作的原因是,对UI所做的每项更改都应在主线程中完成。 If you try to change it in a background thread nothing will happen. 如果您尝试在后台线程中更改它,则不会发生任何事情。

DispatchQueue.main.async {
    self.Setupproductcontainer() 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM