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

Dre*_*ich 4 ios swift rsbarcodes

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

'NSInternalInconsistencyException',原因:'只在主线程上运行!'.

也许这不是验证QR码的正确位置,或者不适合segue,但如果没有,我想知道验证和segue应该在哪里进行.我唯一的另一个要求是验证仅在检测到QR码时才会发生.

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dre*_*ich 8

我在这个问题线程上联系了RSBarcodes_Swift的开发人员.为了执行任何UI操作,需要在主线程上运行.例如,需要更改segue函数:

func performQR(){
        self.performSegueWithIdentifier("toQR", sender: self)
}
Run Code Online (Sandbox Code Playgroud)

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

为了避免在扫描时多次进行segueing,可以在for循环中使用self.session.stopRunning()a和a之间的调用.breakbarcodes

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)