Scan BarCode & QRCode With iPhone Camera Using Swift 4(AVFoundation) - iOS 11 - Swift 4 Tutorials W3Schools

Hot

Post Top Ad

17 Sep 2017

Scan BarCode & QRCode With iPhone Camera Using Swift 4(AVFoundation) - iOS 11

Hello Guys! In this article we will dive in to Bar Code & Qr Code Scanner App. Here we doing both code scanning in single App.

Apple introduced Av Foundation from iOS 7 to support reading bar codes. Apple supports all types of following codes:

AVMetadataObjectTypeUPCECode
AVMetadataObjectTypeCode39Code
AVMetadataObjectTypeCode39Mod43Code
AVMetadataObjectTypeEAN13Code
AVMetadataObjectTypeEAN8Code
AVMetadataObjectTypeCode93Code
AVMetadataObjectTypeCode128Code
AVMetadataObjectTypePDF417Code
AVMetadataObjectTypeQRCode
AVMetadataObjectTypeAztecCode

This Article Covers Following Related questions  :

xcode barcode scanner tutorial
swift barcode scanner github
avfoundation barcode tutorial
ios barcode scanner sdk open source
barcode scanner ios github
swift barcode generator
swift qr code scanner
swift 3 qr code reader
Building a Barcode and QR Code Reader in Swift 3 and Xcode 8
Barcode Scanning in iOS8 With Swift AVFoundation Class




Getting Started :

Create a new project -> open Xcode -> File -> New -> Project -> Single View App, then tap next button. Type product name as 'BarCode&QRCode' then tap next and select the folder to save project.

Firstly for scanning code we need to access device camera's. For that open info.plist and add "Privacy - Camera Usage Description" key with a description "To read BarCode & QRCode".


Privacy - Camera Usage Description
Next import the following framework:
import AVFoundation

Add the following properties before viewDidLoad() function :
var videoCaptureDevice: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var output = AVCaptureMetadataOutput()
var previewLayer: AVCaptureVideoPreviewLayer?

var captureSession = AVCaptureSession()
var code: String?

var scannedCode = UILabel()

Add the following two methods:
private func setupCamera() {
    
    let input = try? AVCaptureDeviceInput(device: videoCaptureDevice)
    
    if self.captureSession.canAddInput(input) {
        self.captureSession.addInput(input)
    }
    
    self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    
    if let videoPreviewLayer = self.previewLayer {
        videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        videoPreviewLayer.frame = self.view.bounds
        view.layer.addSublayer(videoPreviewLayer)
    }
    
    let metadataOutput = AVCaptureMetadataOutput()
    if self.captureSession.canAddOutput(metadataOutput) {
        self.captureSession.addOutput(metadataOutput)
        
        metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeQRCode, AVMetadataObjectTypeAztecCode]
        
    } else {
        print("Could not add metadata output")
    }
}

private func addLabelForDisplayingCode() {
    view.addSubview(scannedCode)
    scannedCode.translatesAutoresizingMaskIntoConstraints = false
    scannedCode.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20.0).isActive = true
    scannedCode.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20.0).isActive = true
    scannedCode.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20.0).isActive = true
    scannedCode.heightAnchor.constraint(equalToConstant: 50).isActive = true
    scannedCode.font = UIFont.preferredFont(forTextStyle: .title2)
    scannedCode.backgroundColor = UIColor.black.withAlphaComponent(0.5)
    scannedCode.textAlignment = .center
    scannedCode.textColor = UIColor.white
    scannedCode.text = "Scanning...."
}

First method is for adding camera and second is for displaying scanned text.

Call the above methods in viewDidLoad() as follow :

self.setupCamera()
self.addLabelForDisplayingCode()

Add the following delegate to ViewController.swift.

AVCaptureMetadataOutputObjectsDelegate

Add the following methods for starting and stopping captureSession.

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    if (captureSession.isRunning == false) {
        captureSession.startRunning();
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    if (captureSession.isRunning == true) {
        captureSession.stopRunning();
    }
}

Then finally add the delegate method as following:
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
    // This is the delegate'smethod that is called when a code is readed
    
    print(metadataObjects)
    for metadata in metadataObjects {
        let readableObject = metadata as! AVMetadataMachineReadableCodeObject
        let code = readableObject.stringValue
        scannedCode.text = code
    }
}

The above method will perform scanning operation and generate the code from the BarCode & QRCodes.


Build and Run, we see camera. Then focus on the barcode, the scanned code will be at the bottom.

Scan BarCode & QRCode With iPhone Camera Using Swift 4(AVFoundation) - iOS 11


You can create your own barcode from here.

Download sample project with example :


2 comments:

  1. Yeah its an amazing qr code for Android. Please i need Lightning QR Code Reader app code. I hope anyone will give me.

    ReplyDelete

Post Top Ad