Data Scanner Demo

Last update: Jun 13, 2022

DataScannerDemo

Hi there thanks for visiting this repo. If you like it I encourage you to please leave a like.

Before

Before iOS 16 it was quite unintuitave and tedious. There was also the difficulty for figuring out how to work this into your flow. The code below will get you up and running prior to iOS 16. But you would quickly see how tedious it is because of the ever publishing delegate method.

    func configureCaptureDevice() {
        startRunningSession()
    
        let metadataOutput = AVCaptureMetadataOutput()
        
        session.sessionPreset = AVCaptureSession.Preset.iFrame1280x720
        
        guard let captureDevice = AVCaptureDevice.default(for: .video), let deviceInput = try? AVCaptureDeviceInput(device: captureDevice) else {
            return
        }
        
        session.addInput(deviceInput)
        session.addOutput(metadataOutput)
        
        configureOutput()
        
        metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        metadataOutput.metadataObjectTypes = [.ean8, .ean13, .pdf417]
        metadataOutput.rectOfInterest = aVCaptureVideoPreviewLayer?.metadataOutputRectConverted(fromLayerRect: CGRect(x: view.frame.width * 0.065, y: view.center.y - 48, width: view.frame.width * 0.85, height: view.frame.width * 0.5)) ?? .zero
    }
    
    private func configureOutput() {
        aVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
        aVCaptureVideoPreviewLayer?.frame = view.frame
        aVCaptureVideoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        
        if let previewLayerUnwrap = aVCaptureVideoPreviewLayer {
            view.layer.addSublayer(previewLayerUnwrap)
        }
    }
}

extension VideoSessionController: AVCaptureMetadataOutputObjectsDelegate {
   
    // MARK: - AVCaptureMetadataOutputObjectsDelegate
    
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        guard let metadataObject = metadataObjects.first else {
            return
        }
        guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else {
            return
        }
        guard let stringValue = readableObject.stringValue else {
            return
        }
        AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
        self.barcodeStringSubject.send(stringValue)
    }
}

After

After iOS 16 we are give an abstracted API to integrate data scanner without the hassles of working with AVFoundation. The code below wraps the new DataScannerViewController in UIViewControllerRepresentable to be able to use it in SwiftUI. I also want to cal out a few thing when using this API.

  1. Apple has nicely integrated Guidance into this controller so it displays on screen prompts to guide the user in a direction which would allow the camera to pickup the target barcode more easily.
  2. In order to receive the value of the scanned barcode the user must tap the screen after the barcode is recognised. There is no on screen prompt to indicate that the scanning has been complete.
  3. If you have enabled isHighlightingEnabled in the initializer of the DataScannerViewController an on screen rectangle will be presented to highlight the frame of the barcode which was scanned, which I think is a nice touch.
  4. Dont forget to set the delegate in order to receive any changes you must set the delegate as an object and conformm to it.
  5. This API is also in beta changes may come to it but not to worry, I will make updates as they arise.
/// A view that allows for the scanning of a barcode.
struct BarcodeScannerView: UIViewControllerRepresentable {
    
    /// Manages the logic related to scanning data.
    @ObservedObject var dataScannerManager: DataScannerManager
    
    func makeUIViewController(context: Context) -> DataScannerViewController {
        let dataScannerViewController = DataScannerViewController(recognizedDataTypes: [.barcode(symbologies: [.upce,.ean8,.ean13])], qualityLevel: .fast, isHighlightingEnabled: true)
        dataScannerViewController.delegate = dataScannerManager
        try? dataScannerViewController.startScanning()
        return dataScannerViewController
    }
    
    func updateUIViewController(_ uiViewController: DataScannerViewController, context: Context) {}
}
/// Manages the properties and methods related to data scanning.
final class DataScannerManager: NSObject, ObservableObject, DataScannerViewControllerDelegate {
    
    /// Value indicating that scanning has failed.
    @Published private(set) var dataScannerFailure: DataScannerViewController.ScanningUnavailable?
    
    /// The string of the recognized barcode.
    @Published var recognisedBarcodeString: String = ""
   
    // MARK: - DataScannerViewControllerDelegate
    
    func dataScanner(_ dataScanner: DataScannerViewController, didTapOn item: RecognizedItem) {
        switch item {
        case .text: break
        case let .barcode(barcode):
            recognisedBarcodeString = barcode.payloadStringValue ?? ""
        @unknown default: break
        }
    }
    
    func dataScanner(_ dataScanner: DataScannerViewController, becameUnavailableWithError error: DataScannerViewController.ScanningUnavailable) {
         self.dataScannerFailure = error
    }
}

Demo

TrimmedVersion.mov

GitHub

https://github.com/ashlirankin18/DataScannerDemo
You might also like...

CoreDataCloudKitShare - Learn how to use Core Data CloudKit

Sharing Core Data Objects Between iCloud Users Implement the flow to share data

Feb 10, 2022

BowTies - The main purpose of this application is to show how you can perform simple operations using Core Data

BowTies - The main purpose of this application is to show how you can perform simple operations using Core Data

BowTies The main purpose of this application is to show how you can perform simp

Jan 31, 2022

rTracker is a complete iOS application for creating local on-device databases ('trackers') to log data with timestamps.

rTracker is a complete iOS application for creating local on-device databases ('trackers') to log data with timestamps.

rTracker is a complete iOS application for creating local on-device databases ('trackers') to log data with timestamps. Trackers can use a va

Jun 14, 2022

:mag_right: A simple and beautiful barcode scanner.

:mag_right: A simple and beautiful barcode scanner.

Description BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience. Barco

Jun 21, 2022

CarBode : Free & Opensource barcode scanner & generator for SwiftUI

CarBode : Free & Opensource barcode scanner & generator for SwiftUI

CarBode Free and Opensource Barcode scanner & Barcode generator for swiftUI Why you must use CarBode CarBode have both Barcode Scanner and Barcode Gen

Jun 5, 2022

SharkCardScan is a Credit/Debit Card scanner built using Apple's Vision Framework.

SharkCardScan is a Credit/Debit Card scanner built using Apple's Vision Framework.

iOS Credit/Debit card scanner, built using Apple's Vision Framework.

Jun 3, 2022

:mag_right: A simple and beautiful barcode scanner.

:mag_right: A simple and beautiful barcode scanner.

Description BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience. Barco

Jun 21, 2022

QR Blank - QR Code URL scanner

 QR Blank - QR Code URL scanner

QR Blank - QR Code URL scanner No Ads, Clean, Simple open source QR Code URL scanner Check URL by Google Safe Browsing before open. Google Safe Browsi

Feb 7, 2022

A simple and beautiful barcode scanner.

A simple and beautiful barcode scanner.

Description BarcodeScanner is a simple and beautiful wrapper around the camera with barcode capturing functionality and a great user experience. Barco

Jun 15, 2022

An iOS LAN Network Scanner library

An iOS LAN  Network Scanner library

MMLanScan MMLanScan is an open source project for iOS that helps you scan your network and shows the available devices and their MAC Address, hostname

Jun 7, 2022

QR Barcode Scanner For Swift

QRBarcodeScanner Example To run the example project, clone the repo, and run pod

Dec 22, 2021

A credit card scanner for iOS written in Swift

A credit card scanner for iOS written in Swift

DGCardScanner A credit card scanner Requirements iOS 13.0+ Swift 5.5+ Xcode 10.0+ Installation SPM File Add Packages https://github.com/donggyushi

Mar 28, 2022

BarcodeScannerSwift - Barcode Scanner Built With Swift

BarcodeScannerSwift This repository was built for a supermarket. Employees can k

Jun 21, 2022

QRCode Scanner using Apple in build Vision framework.

🔲 iOS13 DKQRReader Example A quick example showing how to use the Vision system-framework in iOS 13 and Swift 5. Prerequisites Xcode 13 and later Get

Jun 7, 2022

A Simple iOS QR code scanner that allows users to enable their camera and local Photo Library accesses to scan the contents of the input QR codes.

iOS QR Code Scanner A Simple iOS QR code scanner using Swift UI. Jump to: ContentView.swift screenshot 1.1.5 NOTE: be aware of the new horizontal line

Jun 19, 2022

Px-mobile-sdk-demo-app - PerimeterX Mobile SDK - Demo App

Px-mobile-sdk-demo-app - PerimeterX Mobile SDK - Demo App

About PerimeterX PerimeterX is the leading provider of application security solu

Jan 19, 2022

IOS-App4 - Core Data add new data and update data

IOS-App4 - Core Data add new data and update data

iOS-App4 Core Data add new data and update data.

Jan 8, 2022

This project server as a demo for anyone who wishes to learn Core Data in Swift.

CoreDataDemo This project server as a demo for anyone who wishes to learn Core Data in Swift. The purpose of this project is to help someone new to Co

May 3, 2022

A directory demo app written with SwiftUI, Core Data, and Alamofire

A directory demo app written with SwiftUI, Core Data, and Alamofire

Directory-SwiftUI A directory demo app written with SwiftUI, Core Data, and Alamofire Getting Started Clone (or fork) this repo: git clone [email protected]

Mar 5, 2022
A demo app to showcase pixel perfect, modern iOS development with SwiftUI and Combine on MVVM-C architecture.

Pixel_Perfect_SwiftUI A demo app to showcase pixel perfect, modern iOS development with SwiftUI and Combine on MVVM-C architecture. Tech Stack: Swift,

Jan 9, 2022
An e-commerce app with some function: searching, like product, demo paying and view product

Emarket_060921 An e-commerce app with some function: searching, like product, demo paying and view product. I have developed this app all by myself, b

Jan 17, 2022
🛶Shallows is a generic abstraction layer over lightweight data storage and persistence.

Shallows Shallows is a generic abstraction layer over lightweight data storage and persistence. It provides a Storage<Key, Value> type, instances of w

Jun 16, 2022
Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind
Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind

Disk is a powerful and simple file management library built with Apple's iOS Data Storage Guidelines in mind

Jun 22, 2022
KeyPathKit is a library that provides the standard functions to manipulate data along with a call-syntax that relies on typed keypaths to make the call sites as short and clean as possible.

KeyPathKit Context Swift 4 has introduced a new type called KeyPath, with allows to access the properties of an object with a very nice syntax. For in

Jun 3, 2022
Realm is a mobile database: a replacement for Core Data & SQLite

Realm is a mobile database that runs directly inside phones, tablets or wearables. This repository holds the source code for the iOS, macOS, tvOS & wa

Jun 27, 2022
A library that provides the ability to import/export Realm files from a variety of data container formats.

Realm Converter Realm Converter is an open source software utility framework to make it easier to get data both in and out of Realm. It has been built

Jun 16, 2022
An alternative to Core Data for people who like having direct SQL access.

FCModel 2 An alternative to Core Data for people who like having direct SQL access. By Marco Arment. See the LICENSE file for license info (it's the M

Jun 15, 2022
Your Data Storage Troubleshooter 🛠
Your Data Storage Troubleshooter 🛠

Your Data Storage Troubleshooter ?? Introduction StorageKit is a framework which reduces the complexity of managing a persistent layer. You can easily

Jan 14, 2022
Synco - Synco uses Firebase's Realtime Database to synchronize data across multiple devices, in real time

Synco Synco uses Firebase's Realtime Database to synchronize a color across mult

Feb 7, 2022