Bar Code Scanner | QR Code Scanner in iOS with swift 5

Bar Code Scanner | QR Code Scanner in iOS with swift 5
April 26, 2020 1 Comment Development,iOS Development Pushpendra Kumar

In this tutorial, you will learn the complete functionality of the Bar and QR code scanner. In this tutorial, I have explained this with the help of a basic example. Here I have to use AVCaptureSession and AVCaptureVideoPreviewLayer for achieving our goals. And for your kind information, I would like to tell you that. I did not use any third-party library in this. Because I trust the native functionality and I believe that. If I can perform this action then why not you? So follow the complete tutorial and become an expert in that.

Bar Code Scanner | QR Code Scanner in iOS with swift 5

iOS supports barcode and QR code scanning out of the box. But to be honest it’s not that easy to do. So, here’s a complete UIViewController class that you can add to your ios project and get output with no hassle.

//UPDATED
//  ViewController.swift
//  QR Scanner
//
//  Created by Pushpendra on 26/04/20.
//  Copyright © 2020 Pushpendra. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    var avCaptureSession: AVCaptureSession!
    var avPreviewLayer: AVCaptureVideoPreviewLayer!
    

    override func viewDidLoad() {
        super.viewDidLoad()
        avCaptureSession = AVCaptureSession()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else {
                self.failed()
                return
            }
            let avVideoInput: AVCaptureDeviceInput
            
            do {
                avVideoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
            } catch {
                self.failed()
                return
            }
            
            if (self.avCaptureSession.canAddInput(avVideoInput)) {
                self.avCaptureSession.addInput(avVideoInput)
            } else {
                self.failed()
                return
            }
            
            let metadataOutput = AVCaptureMetadataOutput()
            
            if (self.avCaptureSession.canAddOutput(metadataOutput)) {
                self.avCaptureSession.addOutput(metadataOutput)
                
                metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
                metadataOutput.metadataObjectTypes = [.ean8, .ean13, .pdf417, .qr]
            } else {
                self.failed()
                return
            }
            
            self.avPreviewLayer = AVCaptureVideoPreviewLayer(session: self.avCaptureSession)
            self.avPreviewLayer.frame = self.view.layer.bounds
            self.avPreviewLayer.videoGravity = .resizeAspectFill
            self.view.layer.addSublayer(self.avPreviewLayer)
            self.avCaptureSession.startRunning()
        }
    }
    
    
    func failed() {
        let ac = UIAlertController(title: "Scanner not supported", message: "Please use a device with a camera. Because this device does not support scanning a code", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
        avCaptureSession = nil
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if (avCaptureSession?.isRunning == false) {
            avCaptureSession.startRunning()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        if (avCaptureSession?.isRunning == true) {
            avCaptureSession.stopRunning()
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return true
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
}
extension ViewController : AVCaptureMetadataOutputObjectsDelegate {
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        avCaptureSession.stopRunning()
        
        if let metadataObject = metadataObjects.first {
            guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return }
            guard let stringValue = readableObject.stringValue else { return }
            AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
            found(code: stringValue)
        }
        
        dismiss(animated: true)
    }
    
    func found(code: String) {
        print(code)
    }
}

Great job..😊😊😊😊 After that, Just build and run ▶️ your project. Now you can the output on your screen.

In Conclusion, This is the best and easiest way. I hope it is clear about How to integrate Bar | QR Code Scanner in iOS with a swift 5 programming language. But if still, you have any confusion for the integration then you can visit on my YouTube video. In My Youtube video, I have explained deeply about Bar code scanning and QR Code scanning in this video. And also do not forget to subscribe to my YouTube channel. If you are looking more interesting topic then follow the below links and boost your skills.

Tags
About The Author
Pushpendra Kumar I am passionate about mobile application development and professional developer at Colour Moon Technologies Pvt Ltd (www.thecolourmoon.com). This website I have made so that I can meet with new challenges and can share here.
Leave Comment
  1. 1

    önder Güler

    hey on my iphone just scans barcode ufortunatly doenst scan qr code

    Reply

Leave a reply

Your email address will not be published. Required fields are marked *