Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to scan barcode?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 530
    Comment on it

    This blog includes the concept of scanning the bar codes but before proceeding towards the topics we will discuss bar code. A barcode can be defined as an optical machine-readable representation of data relating to the object to which it is attached. Representation of data by barcodes is done varying the width and spacings of parallel lines.

    If only parallel lines are used those are referred as linear or one-dimensional (1D). Not only one-dimensional representation is there but also two-dimensional codes were developed using rectangles,dots and other geometric patterns. These barcodes were scanned by special scanners known as barcode readers. Here is an example of how to scan barcodes with the help of camera of a phone.



    In this example, we are going to develop an application which is used to scan barcodes with the help of camera of a phone. Start with a new project and include 5 frameworks which are required for further processing.  Frameworks are QuartzCore.framework, Foundation.framework, AVFoundation.framework, CoreGraphics.framework, UIKit.framework. These frameworks will help in fetching the string from bar code. Below are some screenshots which will help us to understand how to add frameworks in a project.

     

    Select project and we will get this kind of screen which is given below. Select Build Phases from this screen so that we can add frameworks required for this application. Select Link Binary With Libraries as we are going to add frameworks from here. Click on plus sign as that was given to add more libraries or frameworks.

     

     

     

     

    After that, we will get this kind of screen with search option. From here we can easily search the framework we want to add. Suppose we want to add AVFoundation framework so search option is available and automatically provide suggestions regarding the search. After getting the accurate search we will select the framework and add to the application.

     

     

     

     

    In this way we will see the added framework in Link Binary With Libraries option as given below:-

     

     

     

    In a similar way, we will add all 5 frameworks required to scan the barcodes and display the string encoded.

     

     

    After adding these 5 frameworks lets start some coding now. First of all take a new file of UIController type named as ScanBarCodeViewController which includes the whole coding to scan a barcode and display string encoded within barcode. As we directly going to the coding part without designing the user interface because we will create user interface in customized way with the help of coding only. Below is the coding of an another file also named as StringDeclaration which help in the declaration of strings we are going to use in the project.

     

    StringDeclaration.h
    
    #import <Foundation/Foundation.h>
    
    @interface StringDeclaration : NSObject
    extern NSString *const message; // constant string is declared here which we can use anywhere in the project after importing this file.
    @end
    
     StringDeclaration.m
    
    #import "StringDeclaration.h"
    
    @implementation StringDeclaration
    NSString * const message=@"(none)"; //definition of the same constant string declared in the interface part of file.
    @end

     


    Here is the ScanBarCodeViewController file which includes the whole coding to scan barcode. AVCaptureMetadataOutputObjectsDelegate delegate is used in the interface part of the file so that we are able to access the method declared inside this delegate.

     

    ScanBarCodeViewController.h
    
    
    #import <UIKit/UIKit.h>
    #import <AVFoundation/AVFoundation.h>
    #import "StringDeclaration.h"
    @interface ScanBarCodeViewController : UIViewController<AVCaptureMetadataOutputObjectsDelegate>
    
    @end
    
    
    ScanBarCodeViewController.m
    
    
    #import "ScanBarCodeViewController.h"
    
    @interface ScanBarCodeViewController ()
    {
        AVCaptureSession *_captureSession;
        AVCaptureDevice *_captureDevice;
        AVCaptureDeviceInput *_captureDeviceInput;
        AVCaptureMetadataOutput *_captureMetadataOutput;
        AVCaptureVideoPreviewLayer *_prevLayer;
        
        UIView *_highlightedView;
        UILabel *_lblMessage;
    }
    @end
    
    @implementation ScanBarCodeViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        _highlightedView = [[UIView alloc] init];
        _highlightedView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
        _highlightedView.layer.borderColor = [UIColor greenColor].CGColor;
        _highlightedView.layer.borderWidth = 3;
        [self.view addSubview:_highlightedView];
        
        _lblMessage = [[UILabel alloc] init];
        _lblMessage.frame = CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40);
        _lblMessage.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        _lblMessage.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65];
        _lblMessage.textColor = [UIColor whiteColor];
        _lblMessage.textAlignment = NSTextAlignmentCenter;
        _lblMessage.text = message;
        [self.view addSubview:_lblMessage];
        
        _captureSession = [[AVCaptureSession alloc] init];
        _captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
        NSError *error = nil;
        
        _captureDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:_captureDevice error:&error];
        if (_captureDeviceInput) {
            [_captureSession addInput:_captureDeviceInput];
        } else {
            NSLog(@"Error: %@", error);
        }
        
        _captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
        [_captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
        [_captureSession addOutput:_captureMetadataOutput];
        
        _captureMetadataOutput.metadataObjectTypes = [_captureMetadataOutput availableMetadataObjectTypes];
        
        _prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_captureSession];
        _prevLayer.frame = self.view.bounds;
        _prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [self.view.layer addSublayer:_prevLayer];
        
        [_captureSession startRunning];
        
        [self.view bringSubviewToFront:_highlightedView];
        [self.view bringSubviewToFront:_lblMessage];
        // Do any additional setup after loading the view.
    }
    
    - (void)didReceiveMemoryWarning {
        [super didReceiveMemoryWarning];
        // Dispose of any resources that can be recreated.
    }
    
    - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
    {
        CGRect highlightViewRect = CGRectZero;
        AVMetadataMachineReadableCodeObject *barCodeObject;
        NSString *detectionString = nil;
        NSArray *barCodeTypes = @[AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code,
                                  AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code,
                                  AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode];
        
        for (AVMetadataObject *metadata in metadataObjects) {
            for (NSString *type in barCodeTypes) {
                if ([metadata.type isEqualToString:type])
                {
                    barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
                    NSLog(@"%@",barCodeObject);
                    highlightViewRect = barCodeObject.bounds;
                    detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
                    NSLog(@"%@",detectionString);
                    break;
                }
            }
            
            if (detectionString != nil)
            {
                _lblMessage.text = detectionString;
                break;
            }
            else
                _lblMessage.text = message;
        }
        
        _highlightedView.frame = highlightViewRect;
    }
    
    @end

     

     

    Output:-


    This kind of output we will get if application get executed in the system which is given below:-

     

    2016-06-06 12:30:39.560 SampleScanBarCode[17424:153246] Error: Error Domain=AVFoundationErrorDomain Code=-11814 "Cannot Record" UserInfo={NSLocalizedDescription=Cannot Record, NSLocalizedRecoverySuggestion=Try recording again.}

     

    To get the accurate output we need a device and with the help of device we can check whether camera is detecting any barcode visible and providing the string or not.

     

    2016-06-06 12:57:32.689 SampleScanBarCode[225:10020] <AVMetadataMachineReadableCodeObject: 0x1702202a0, type="org.gs1.EAN-13", bounds={ 116.9,239.3 65.9x2.5 }>corners { 116.9,239.3 116.9,241.7 182.8,241.7 182.8,239.2 }, time 1558451853625, stringValue "9501101530003"

     

    As we have used NSLog to display the string encoded within the barcode that is why in this way we will get the output. We can also see the same string at bottom of the screen of device. You can also download the project with the help of link given below :-

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: