Data Scanner Demo

Overview

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
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

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

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

A GUI for dynamically creating NSPredicates at runtime to query data in your iOS app.
A GUI for dynamically creating NSPredicates at runtime to query data in your iOS app.

PredicateEditor PredicateEditor is a visual editor for creating and using NSPredicates for querying data in your app. PredicateEditor was inspired by

Realm-powered Core Data persistent store
Realm-powered Core Data persistent store

RealmIncrementalStore Realm-powered Core Data persistent store Wait, what? I like Realm. Realm's memory-mapped DB blows other databases out of the wat

This project has been developed to understand GraphQL and Diffable Data Source. Created on 20.06.2022.

SpaceX Launches First in first. You need to build all packages before building the project. Packages: Extensions API Open Extensions folder under proj

: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

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

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.

: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

 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

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

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

QR Barcode Scanner For Swift

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

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

BarcodeScannerSwift - Barcode Scanner Built With Swift

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

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

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

Scanner for decks of cards with bar codes printed on card edges
Scanner for decks of cards with bar codes printed on card edges

The Nettle Magic Project This deck of cards has a bar code printed on the edge of each card. Scanning these bar codes would reveal where every card is

Owner
Ashli Rankin
Ashli Rankin
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,

Burhan Aras 0 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

null 0 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

Oleg Dreyman 620 Dec 3, 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

Saoud Rizwan 3k Jan 3, 2023
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

Vincent Pradeilles 406 Dec 25, 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

Realm 15.7k Jan 1, 2023
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

Realm 212 Dec 9, 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

null 1.7k Dec 28, 2022
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

StorageKit 231 Dec 29, 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

Alessio 0 Feb 7, 2022