使用 RSBarcodes 扫描条形码时执行操作

Perform Action When a Barcode Is Scanned Using RSBarcodes

我正在构建一个使用 RSBarcodes for Swift 扫描二维码的应用程序。我在 ScanViewController 中尝试做的是扫描二维码,验证扫描的内容,然后使用扫描的数据进行搜索。目前,当检测到 QR 码时,我的 UI 冻结,并且在我收到错误和内存转储后不久:

'NSInternalInconsistencyException', reason: 'Only run on the main thread!'.

也许这不是验证 QR 码的正确位置或不是正确的 segue 位置,但如果不是,我想知道验证和 segue 应该在哪里进行。我唯一的其他要求是验证仅在检测到二维码时发生。

class ScanViewController: RSCodeReaderViewController{
    // Class Variables
    var finalObject: IBuiltCode?
    let ObjectHelper = ObjectBuilder() // Service to validate and build valid scanned objects

    override func viewDidLoad() {
        super.viewDidLoad()

        self.focusMarkLayer.strokeColor = UIColor.redColor().CGColor
        self.cornersLayer.strokeColor = UIColor.yellowColor().CGColor

        self.tapHandler = { point in
            println(point)
        }

        self.barcodesHandler = { barcodes in
            for barcode in barcodes {
                println("Barcode found: type=" + barcode.type + " value=" + barcode.stringValue)
                if let builtObject = self.ObjectHelper.validateAndBuild(barcode,
                      scannedData: barcode.stringValue){
                    println("Good object.")
                    self.performQR()
                }
            }
        }
    }

    func performQR(){
        performSegueWithIdentifier("toQR", sender: self)
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == "toQR"){
            let QRVC: QRViewController = segue.destinationViewController as! QRViewController
            QRVC.receivedObject = finalObject as? QRObject
        }
    }
}

我在 this issue 线程上联系了 RSBarcodes_Swift 的开发者。为了执行任何 UI 操作,它需要在主线程上 运行 。比如segue函数需要改成:

func performQR(){
        self.performSegueWithIdentifier("toQR", sender: self)
}

func performQR(){
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.performSegueWithIdentifier("toQR", sender: self)
    })
}

为了避免扫描时多次转场,可以在 barcodes for 循环中使用调用 self.session.stopRunning()break

self.barcodesHandler = { barcodes in
    for barcode in barcodes {
        println("Barcode found: type=" + barcode.type + " value=" + barcode.stringValue)
        if let builtObject = self.ObjectHelper.validateAndBuild(barcode,
              scannedData: barcode.stringValue){
            println("Good object.")
            self.finalObject = builtObject
            self.session.stopRunning() // Avoid scanning multiple times
            self.performQR()
            break
        }
    }
}