如何使用Swift 3扫描条形码照片?

时间:2017-12-14 22:13:28

标签: ios swift barcode

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

    if let metadataObject = metadataObjects.first {
        let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;

        AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
        found(code: readableObject.stringValue!);
    }
}

以上功能完美无缺但我试图获得扫描结果并将其作为照片写入设备但现在似乎不可能。

1 个答案:

答案 0 :(得分:0)

这样做的方法是使用CoreImage。当您获得readableObject.stringValue后,您会使用过滤器CICode128BarcodeGenerator生成图片。

所以,在你的例子中:

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

    if let metadataObject = metadataObjects.first {
        let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;

        let barcodeFilter = CIFilter(name: "CICode128BarcodeGenerator")
        barcodeFilter?.setValue(readableObject.stringValue!.data(using: .ascii), forKey: "inputMessage")

        let image = UIImage(ciImage: (barcodeFilter?.outputImage)!)

        AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
        found(code: readableObject.stringValue!);
    }
}

请记住文件开头的import CoreImage