如何在iOS上扫描条形码?

Ste*_*fan 188 iphone cocoa-touch barcode ios swift

如何在iPhone和/或iPad上简单扫描条形码?

小智 81

查看ZBar读取QR码和ECN/ISBN代码,可在LGPL v2许可下获得.

  • 部分正确.ZBar.app是根据Apache许可证(版本2.0)许可的,但*library*是根据LGPL v2许可的. (5认同)
  • 遗憾的是,许可证要求您与任何请求它们的人共享您的应用程序的目标文件.请查看http://zbar.sourceforge.net/iphone/sdkdoc/licensing.html (3认同)

Sea*_*wen 80

我们为iPhone制作了"条形码"应用程序.它可以解码QR码.源代码可从zxing项目获得 ; 具体来说,您要查看iPhone客户端核心库部分C++端口.该端口有点陈旧,大约是Java代码的0.9版本,但仍然应该运行得相当好.

如果需要扫描其他格式(如1D格式),可以将此项目中的Java代码端口继续到C++.

编辑:iphone项目中的条形码和代码在2014年初退役.


Ale*_*der 55

与发布时一样,iOS7您不再需要使用外部框架或库.拥有AVFoundation的iOS生态系统现在完全支持扫描从EAN到UPC的QR中的几乎所有代码.

只需看看Tech Note和AVFoundation编程指南.AVMetadataObjectTypeQRCode是你的朋友.

这是一个很好的教程,一步一步地显示它: iPhone QR码扫描库iOS7

关于如何设置它的一个小例子:

#pragma mark -
#pragma mark AVFoundationScanSetup

- (void) setupScanner;
{
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];

    self.session = [[AVCaptureSession alloc] init];

    self.output = [[AVCaptureMetadataOutput alloc] init];
    [self.session addOutput:self.output];
    [self.session addInput:self.input];

    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];

    self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.preview.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    AVCaptureConnection *con = self.preview.connection;

    con.videoOrientation = AVCaptureVideoOrientationLandscapeLeft;

    [self.view.layer insertSublayer:self.preview atIndex:0];
}
Run Code Online (Sandbox Code Playgroud)


Ari*_*tee 13

iPhone 4相机不仅仅是做条码的能力.斑马线条形码库在github zxing-iphone上有一个分叉.它是开源的.

  • github fork似乎已经死了,正如本期所述:https://github.com/joelind/zxing-iphone/issues/3 (4认同)

Jos*_*own 10

liteqr是github上"从zxing移植的Objective C中的Lite QR阅读器",支持Xcode 4.


Mon*_*art 10

有两个主要的图书馆:

  • ZXing用Java编写的库,然后移植到Objective C/C++(仅限QR代码).另一个到ObjC的端口已由TheLevelUp:ZXingObjC完成

  • ZBar是一款用于读取条形码的开源软件,基于C语言.

根据我的实验,ZBar比ZXing 更准确,更快,至少在iPhone上.


abd*_*lek 6

您可以在下面找到使用Swift 4Xcode 9的另一个本机iOS解决方案。AVFoundation此解决方案中使用的本机框架。

第一部分是的子类UIViewController,具有用于的相关设置和处理函数AVCaptureSession

import UIKit
import AVFoundation

class BarCodeScannerViewController: UIViewController {

    let captureSession = AVCaptureSession()
    var videoPreviewLayer: AVCaptureVideoPreviewLayer!
    var initialized = false

    let barCodeTypes = [AVMetadataObject.ObjectType.upce,
                        AVMetadataObject.ObjectType.code39,
                        AVMetadataObject.ObjectType.code39Mod43,
                        AVMetadataObject.ObjectType.code93,
                        AVMetadataObject.ObjectType.code128,
                        AVMetadataObject.ObjectType.ean8,
                        AVMetadataObject.ObjectType.ean13,
                        AVMetadataObject.ObjectType.aztec,
                        AVMetadataObject.ObjectType.pdf417,
                        AVMetadataObject.ObjectType.itf14,
                        AVMetadataObject.ObjectType.dataMatrix,
                        AVMetadataObject.ObjectType.interleaved2of5,
                        AVMetadataObject.ObjectType.qr]

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        setupCapture()
        // set observer for UIApplicationWillEnterForeground, so we know when to start the capture session again
        NotificationCenter.default.addObserver(self,
                                           selector: #selector(willEnterForeground),
                                           name: .UIApplicationWillEnterForeground,
                                           object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // this view is no longer topmost in the app, so we don't need a callback if we return to the app.
        NotificationCenter.default.removeObserver(self,
                                              name: .UIApplicationWillEnterForeground,
                                              object: nil)
    }

    // This is called when we return from another app to the scanner view
    @objc func willEnterForeground() {
        setupCapture()
    }

    func setupCapture() {
        var success = false
        var accessDenied = false
        var accessRequested = false

        let authorizationStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if authorizationStatus == .notDetermined {
            // permission dialog not yet presented, request authorization
            accessRequested = true
            AVCaptureDevice.requestAccess(for: .video,
                                      completionHandler: { (granted:Bool) -> Void in
                                          self.setupCapture();
            })
            return
        }
        if authorizationStatus == .restricted || authorizationStatus == .denied {
            accessDenied = true
        }
        if initialized {
            success = true
        } else {
            let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera,
                                                                                        .builtInTelephotoCamera,
                                                                                        .builtInDualCamera],
                                                                          mediaType: .video,
                                                                          position: .unspecified)

            if let captureDevice = deviceDiscoverySession.devices.first {
                do {
                    let videoInput = try AVCaptureDeviceInput(device: captureDevice)
                    captureSession.addInput(videoInput)
                    success = true
                } catch {
                    NSLog("Cannot construct capture device input")
                }
            } else {
                NSLog("Cannot get capture device")
            }
        }
        if success {
            DispatchQueue.global().async {
                self.captureSession.startRunning()
                DispatchQueue.main.async {
                    let captureMetadataOutput = AVCaptureMetadataOutput()
                    self.captureSession.addOutput(captureMetadataOutput)
                    let newSerialQueue = DispatchQueue(label: "barCodeScannerQueue") // in iOS 11 you can use main queue
                    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: newSerialQueue)
                    captureMetadataOutput.metadataObjectTypes = self.barCodeTypes
                    self.videoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
                    self.videoPreviewLayer.videoGravity = .resizeAspectFill
                    self.videoPreviewLayer.frame = self.view.layer.bounds
                    self.view.layer.addSublayer(self.videoPreviewLayer)
                } 
            }
            initialized = true
        } else {
            // Only show a dialog if we have not just asked the user for permission to use the camera.  Asking permission
            // sends its own dialog to th user
            if !accessRequested {
                // Generic message if we cannot figure out why we cannot establish a camera session
                var message = "Cannot access camera to scan bar codes"
                #if (arch(i386) || arch(x86_64)) && (!os(macOS))
                    message = "You are running on the simulator, which does not hae a camera device.  Try this on a real iOS device."
                #endif
                if accessDenied {
                    message = "You have denied this app permission to access to the camera.  Please go to settings and enable camera access permission to be able to scan bar codes"
                }
                let alertPrompt = UIAlertController(title: "Cannot access camera", message: message, preferredStyle: .alert)
                let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                    self.navigationController?.popViewController(animated: true)
                })
                alertPrompt.addAction(confirmAction)
                self.present(alertPrompt, animated: true, completion: nil)
            }
        }
    }

    func handleCapturedOutput(metadataObjects: [AVMetadataObject]) {
        if metadataObjects.count == 0 {
            return
        }

        guard let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject else {
            return
        }

        if barCodeTypes.contains(metadataObject.type) {
            if let metaDataString = metadataObject.stringValue {
                captureSession.stopRunning()
                displayResult(code: metaDataString)
                return
            }
        }
    }

    func displayResult(code: String) {
        let alertPrompt = UIAlertController(title: "Bar code detected", message: code, preferredStyle: .alert)
        if let url = URL(string: code) {
            let confirmAction = UIAlertAction(title: "Launch URL", style: .default, handler: { (action) -> Void in
                UIApplication.shared.open(url, options: [:], completionHandler: { (result) in
                    if result {
                        NSLog("opened url")
                    } else {
                        let alertPrompt = UIAlertController(title: "Cannot open url", message: nil, preferredStyle: .alert)
                        let confirmAction = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                        })
                        alertPrompt.addAction(confirmAction)
                        self.present(alertPrompt, animated: true, completion: {
                            self.setupCapture()
                        })
                    }
                })        
            })
            alertPrompt.addAction(confirmAction)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
            self.setupCapture()
        })
        alertPrompt.addAction(cancelAction)
        present(alertPrompt, animated: true, completion: nil)
    }

}
Run Code Online (Sandbox Code Playgroud)

第二部分是UIViewController子类的扩展,用于AVCaptureMetadataOutputObjectsDelegate捕获捕获的输出。

extension BarCodeScannerViewController: AVCaptureMetadataOutputObjectsDelegate {

    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        handleCapturedOutput(metadataObjects: metadataObjects)
    }

}
Run Code Online (Sandbox Code Playgroud)

Swift 4.2更新

.UIApplicationWillEnterForeground更改为UIApplication.willEnterForegroundNotification


lex*_*exx 5

不确定这是否有帮助,但这里是一个开源QR码库的链接.正如你所看到的,有几个人已经用它来为iPhone创建应用程序.

维基百科有一篇文章解释了什么是QR码.在我看来,QR码比ip​​hone所关注的标准条码更适合用途,因为它是为这种类型的实现而设计的.


小智 5

如果对iPad 2或iPod Touch的支持对您的应用程序很重要,我会选择条形码扫描仪SDK来解码模糊图像中的条形码,例如我们的Scandit条形码扫描仪SDK for iOS和Android.解码模糊条形码图像对于具有自动对焦相机的手机也很有用,因为用户无需等待自动对焦启动.

Scandit提供免费的社区价格计划,还有一个产品API,可以很容易地将条形码数字转换为产品名称.

(免责声明:我是Scandit的联合创始人)