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!);
}
}
上面的功能可以正常工作,但是我试图获取扫描结果并将其写为设备中的照片,但目前看来还不可能。
最佳答案
这样做的方法是使用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
。