我是Ios的新手。我正在学习迅速而被忽视的对象c。
目前,我正在使用swift和xcode 6.1编写演示,可以扫描来自摄像头的qrcode和条形码或来自图像库的图像。
我知道AVFoundation框架支持扫描qrcode和条形码,但它只能从相机扫描。
我搜索并找到zbarSDK,它支持来自摄像头和图像的扫描码。我按照http://zbar.sourceforge.net/iphone/sdkdoc/和NSFastEnumeration in Swift中的说明进行操作(将代码转换为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周)。 感谢。
答案 0 :(得分:12)
我还想从图像中读取QR码而没有Zbar。
您可以改用CIDetector
。我找到了解决方案here。
在我的情况下,我从图书馆中选取一张照片(假设是QR码,此处为qrcodeImg
),然后在CIImage
中将其转换为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)")
}
答案 1 :(得分:0)
对于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)
}