我写了一个小 ios 应用程序来扫描 ean13 条形码,关于灵敏度有一个奇怪的问题,它可以从制造商在产品上打印好的条形码的产品中读取 100% 的 ean13 条形码,例如,CD盒子,药盒,巧克力,黄油,茶叶盒...,但是如果条形码是手动打印的,而不是制造商的条形码打印。那么读取条码就会出现问题,但是这些条码是有效的 ean13 条码,并且可以通过条码阅读器设备硬件轻松读取,甚至可以通过我从苹果商店下载的一些条码扫描应用程序读取,例如,二维码机器人。
例如,下图是手动打印的 ean13 条码,它是有效的 ean13 条码,可以通过条码阅读器硬件轻松读取,也可以通过从应用商店下载的 QRbot 应用程序读取。但无法从我使用 AVFoundation 编写的应用程序中读取它。
以下是完整的代码:
import UIKit
import AVFoundation
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet weak var scanFrame: UIImageView!
var video = AVCaptureVideoPreviewLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let session = AVCaptureSession()
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do
{
let input = try AVCaptureDeviceInput(device: captureDevice)
session.addInput(input)
}
catch
{
print ("Error opening device")
}
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObjectTypeEAN13Code]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
self.view.bringSubview(toFront: scanFrame)
session.startRunning()
output.rectOfInterest = video.metadataOutputRectOfInterest(for: scanFrame.frame)
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
if metadataObjects != nil && metadataObjects.count != 0
{
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
{
if object.type == AVMetadataObjectTypeEAN13Code
{
let alert = UIAlertController(title: "QR Code", message: object.stringValue, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Scan again?", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Copy to clipboard", style: .default, handler: { (nil) in
UIPasteboard.general.string = object.stringValue
}))
print(object.stringValue)
present(alert, animated: true, completion: nil)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
提前致谢!