扫描从快照中从图像库中拾取的相机和图像的qrcode和条形码

我是Ios的新手。 我正在学习迅速和被忽视的对象c。

目前,我正在编写一个带有swift和xcode 6.1的演示程序,它可以扫描来自摄像头的qrcode和条形码或来自图像库的图像。

我知道AVFoundation框架支持扫描qrcode和条形码,但它只能从相机扫描。

我搜索并找到zbarSDK,它支持来自摄像头和图像的扫描码。 我在http://zbar.sourceforge.net/iphone/sdkdoc/和Swift中的NSFastEnumeration中执行指令(将代码转换为swift)。 但是,当我运行app时,从库中选择图像后,就会发生错误。

这是我的代码

import UIKit import AVFoundation extension ZBarSymbolSet: SequenceType { public func generate() -> NSFastGenerator { return NSFastGenerator(self) } } class FirstViewController: UIViewController, ZBarReaderDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { let reader = ZBarReaderController() @IBOutlet weak var lblResult: UILabel! @IBOutlet weak var imgView: UIImageView! override func viewDidLoad() { super.viewDidLoad() reader.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func scanCode(sender: AnyObject) { let scanner = reader.scanner scanner.setSymbology(ZBAR_I25, config: ZBAR_CFG_ENABLE, to: 0) reader.modalPresentationStyle = .Popover presentViewController(reader, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { var results: NSFastEnumeration = info["ZBarReaderControllerResults"] as NSFastEnumeration var symbolFound : ZBarSymbol? // =============== Error here ================== for symbol in results as ZBarSymbolSet { symbolFound = symbol as? ZBarSymbol break } var resultString = NSString(string: symbolFound!.data) println(resultString) } } 

这是错误图像 在此处输入图像描述

如果有人让我知道它为什么会发生错误以及如何修复它或者有任何方法使用AVFoundation扫描代码或者使用其他库(带有详细文档和样本)来执行此操作(请提供详细说明),我将非常感激因为我刚刚学会了swift和ios 3周)。 谢谢。

我还想从图像中读取QR码而没有Zbar。

您可以改用CIDetector 。 我在这里找到了解决方案。 在我的情况下,我从库中获取一张照片(假设是QR码,这里是qrcodeImg ),然后在CIImage qrcodeImg其转换为由CIDetector解码。

 qrCodeImageView.image=qrcodeImg let detector:CIDetector=CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh]) let ciImage:CIImage=CIImage(image:qrcodeImg) var qrCodeLink="" let features=detector.featuresInImage(ciImage) for feature in features as! [CIQRCodeFeature] { qrCodeLink += feature.messageString } if qrCodeLink=="" { print("nothing") }else{ print("message: \(qrCodeLink)") } 

对于Swift3以下代码应该可以帮助您从ZBarSDK获取结果

 extension ZBarSymbolSet: Sequence { public func makeIterator() -> NSFastEnumerationIterator { return NSFastEnumerationIterator(self) } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { // ADD: get the decode results let results: NSFastEnumeration = info[ZBarReaderControllerResults] as! NSFastEnumeration var symbolFound : ZBarSymbol? for symbol in results as! ZBarSymbolSet { symbolFound = symbol as? ZBarSymbol break } let resultString = symbolFound!.data print(resultString) }