CarBode : Free & Opensource barcode scanner & generator for SwiftUI

Overview

CarBode

DonateLink

CarBode

Free and Opensource Barcode scanner & Barcode generator for swiftUI

CarBodeDemo

Why you must use CarBode

  1. CarBode have both Barcode Scanner and Barcode Generator
  2. CarBode is a lightweight components
  3. CarBode build on AVFoundation it will supported all of barcodes types that AVFoundation supported
  4. CarBode can turn on the torch light and it can toggle between front and back camera

Supported Barcode

index

Installation

The preferred way of installing SwiftUIX is via the Swift Package Manager.

Xcode 11 integrates with libSwiftPM to provide support for iOS, watchOS, and tvOS platforms.

  1. In Xcode, open your project and navigate to FileSwift PackagesAdd Package Dependency...
  2. Paste the repository URL (https://github.com/heart/CarBode-Barcode-Scanner-For-SwiftUI) and click Next.
  3. For Rules, select Branch (with branch set to 2.1.2 ).
  4. Click Finish.

Example project

CarBode-Barcode-Scanner-For-SwiftUI/ExampleProject/ExampleProject.xcodeproj

Carbode Example project

How to use Scanner View

SwiftUI QRCode Scanner

Add camera usage description to your info.plist

<key>NSCameraUsageDescription</key>
<string>This app needs access to the camera, to be able to read barcodes.</string>

Simple Scanner

import SwiftUI
import CarBode
import AVFoundation //import to access barcode types you want to scan

struct ContentView: View {

    var body: some View {
        VStack{

        CBScanner(
                supportBarcode: .constant([.qr, .code128]), //Set type of barcode you want to scan
                scanInterval: .constant(5.0) //Event will trigger every 5 seconds
            ){
                //When the scanner found a barcode
                print("BarCodeType =",$0.type.rawValue, "Value =",$0.value)
            }

    }
}

Draw box around the barcode

import SwiftUI
import CarBode
import AVFoundation //import to access barcode types you want to scan

struct ContentView: View {
    var body: some View {
        VStack{
        CBScanner(
                supportBarcode: .constant([.qr, .code128]), //Set type of barcode you want to scan
                scanInterval: .constant(5.0) //Event will trigger every 5 seconds
            ){
                //When the scanner found a barcode
                print("BarCodeType =",$0.type.rawValue, "Value =",$0.value)
            }
            onDraw: {
                print("Preview View Size = \($0.cameraPreviewView.bounds)")
                print("Barcode Corners = \($0.corners)")
                
                //line width
                let lineWidth = 2 

                //line color
                let lineColor = UIColor.red 

                //Fill color with opacity
                //You also can use UIColor.clear if you don't want to draw fill color
                let fillColor = UIColor(red: 0, green: 1, blue: 0.2, alpha: 0.4)
                
                //Draw box
                $0.draw(lineWidth: lineWidth, lineColor: lineColor, fillColor: fillColor)
            }
    }
}

How to turn torch light on/off

import SwiftUI
import CarBode
import AVFoundation //import to access barcode types you want to scan

@State var torchIsOn = false

struct ContentView: View {
    var body: some View {
        VStack{

        Button(action: {
            self.torchIsOn.toggle() //Toggle On/Off
        }) {
            Text("Toggle Torch Light")
        }
            
        Spacer()
        
        CBScanner(
                supportBarcode: .constant([.qr, .code128]), //Set type of barcode you want to scan
                scanInterval: .constant(5.0), //Event will trigger every 5 seconds
                torchLightIsOn: $torchIsOn // Bind a Bool to enable/disable torch light
            ){
                //When the scanner found a barcode
                print("BarCodeType =",$0.type.rawValue, "Value =",$0.value)
            }
        }
    }
}

Switch to front camera

import SwiftUI
import CarBode
import AVFoundation //import to access barcode types you want to scan

@State var torchIsOn = false

struct ContentView: View {
    var body: some View {
        VStack{

        @State var cameraPosition = AVCaptureDevice.Position.back

        // Click to Toggle camera
        Button(action: {
            if cameraPosition == .back {
                cameraPosition = .front
            }else{
                cameraPosition = .back
            }
        }) {
            if cameraPosition == .back{
                Text("Swicth Camera to Front")
            }else{
                Text("Swicth Camera to Back")
            }
        }
            
        Spacer()
        
        CBScanner(
                supportBarcode: .constant([.qr, .code128]), //Set type of barcode you want to scan
                scanInterval: .constant(5.0), //Event will trigger every 5 seconds
                
                cameraPosition: $cameraPosition  //Bind to switch front/back camera
            ){
                //When the scanner found a barcode
                print("BarCodeType =",$0.type.rawValue, "Value =",$0.value)
            }
        }
    }
}

Test on iOS simulator

The iOS simulator doesn't support the camera yet but you can set a mock barcode for iOS simulator.

No need to remove the mock barcode from the production app it will only use for iOS simulator.

    CBScanner(
        supportBarcode: .constant([.qr, .code128]), //Set type of barcode you want to scan
        scanInterval: .constant(5.0), //Event will trigger every 5 seconds
        mockBarCode: .constant(BarcodeData(value:"Mocking data", type: .qr))
    ){
        //When you click the button on screen mock data will appear here
        print("BarCodeType =",$0.type.rawValue, "Value =",$0.value)
    }

Barcode Types Support

Read here https://developer.apple.com/documentation/avfoundation/avmetadataobject/objecttype

How to use barcode generator view

SwiftUI QRCode Scanner

Example code

import SwiftUI

struct ModalBarcodeGenerator: View {
    @State var dataString = "Hello Carbode"
    @State var barcodeType = CBBarcodeView.BarcodeType.qrCode
    @State var rotate = CBBarcodeView.Orientation.up

    var body: some View {
        var body: some View {
            VStack {
                CBBarcodeView(data: $dataString,
                              barcodeType: $barcodeType,
                              orientation: $rotate)
                    .frame(minWidth: 0, maxWidth: .infinity, minHeight: 400, maxHeight: 400, alignment: .topLeading)
            }
        }
    }
}

Barcode type you can generate

//QR Code
// CBBarcodeView.BarcodeType.qrCode
//Code 128
// CBBarcodeView.BarcodeType.barcode128
//Aztec Code
// CBBarcodeView.BarcodeType.aztecCode
//PDF417
// CBBarcodeView.BarcodeType.PDF417

@State var barcodeType = CBBarcodeView.BarcodeType.qrCode
CBBarcodeView(data: ..... ,
                barcodeType: $barcodeType ,
                orientation: ... )

Rotate your barcode

/*Youcan rotate 4 directions
CBBarcodeView.Orientation.up
CBBarcodeView.Orientation.down
CBBarcodeView.Orientation.left
CBBarcodeView.Orientation.right*/

@State var rotate = CBBarcodeView.Orientation.left
CBBarcodeView(data: ..... ,
                barcodeType: ..... ,
                orientation: $rotate)

Contributing

CarBode welcomes contributions in the form of GitHub issues and pull-requests.

Changelog

- 2.1.2 When scan on difference barcode scanner will ignore the delay time
- 2.1.1 Fixed bugs
- 2.1.0 You can draw a box around the barcode
- 2.0.1 Fixed bugs
- 2.0.0 I learned many more things about SwiftUI then I decide to restructure the scanner I hope you will like it. And this version you can switch front and back camera.
- 1.5.0 Fixed bugs and you can read the barcode type when scanner found it
- 1.4.0 Rename component and add new barcode generator view component
- 1.3.0 You can set a mock barcode when running with an iOS simulator.
- 1.2.0 Add feature allows to turn torch light on or off.
- 1.0.1 Fixed bug camera delay 10 seconds when use on modal.
Comments
  • View takes long Time (async)

    View takes long Time (async)

    Hello, the View to load the Scanner takes long time till to init the cam. is there a way to init the cam after the view is presenting? hope you know what i mean. Like Async

    opened by lutzmuschischutz 6
  • Slow closing of camera

    Slow closing of camera

    Hi,

    I am using the scanner in a NavigationView -> NavigationLink. If I open the camera from here it works fine. When I want to close it by clicking the back arrow in NavigationView, it takes about 5 secs to close (showing the gray background meanwhile). Do other experience this also - or do I have (probably) some error in my code? :)

    Thanks, Jens

    opened by ghost 6
  • Incorrect Camera Orientation in Landscape on iPhone and iPad

    Incorrect Camera Orientation in Landscape on iPhone and iPad

    I saw there was a previously closed issue about camera orientation, but I am having an issue with version 2.2.2 where if I start a scan while the device is in landscape mode, the camera will be sideways. If I start a scan in portrait and rotate to landscape on an iPhone, the camera appears to rotate the image to the correct orientation. If I test on an iPad (12.9" Pro running 14.6), the camera is always sideways in landscape mode.

    I'm happy to help test and do anything I can to track down this bug. Thanks.

    opened by MikeMilzz 5
  • Exporting Barcode Image

    Exporting Barcode Image

    Hello! Thanks so much for adding code in 2.2 to access the image file... however, I can't seem to actually get it to save to the camera roll... I'm trying with a very basic Button(action: { UIImageWriteToSavedPhotosAlbum(self.barcodeImage!, nil, nil, nil) } and it asks for camera access and completes the action, but nothing actually shows up in the camera roll... Can I not access the image this way? I'm sorry for my confusion, I'm relatively new to swift and can't figure out how to access the QR code to export it out of the app (which I'm assuming is something you want it to be able to do!) Thanks, Zack

    opened by zfisher323 5
  • Export Generated Barcode to Printer or Camera Roll

    Export Generated Barcode to Printer or Camera Roll

    Hi! Love the code... quick question. I would really like to be able to export the generated barcode to a printer or camera roll...

    Is that something you could add? I was hoping I could just use something like the following extension: extension UIImage { convenience init(view: CBBarcodeView) { UIGraphicsBeginImageContext(view.frame.size) view.layer.render(in:UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.init(cgImage: image!.cgImage!) } }

    And then turn CBBarcodeView into an image that I could export, but CBBarcodeView doesn't have a size or layer for the UIGraphiucsBeginImageContext call...

    Thoughts? Thanks again! Zack

    opened by zfisher323 3
  • iOS 14 beta

    iOS 14 beta

    I've tried my app on iOS 14 beta and is working in a strange way.

    If I open the View that contains Carbode it takes a photo immediately, is not waiting to recognize de barcode.

    I think that you should probably know.

    opened by beboprich 3
  • 10 second delay when showing CarBode view using modal .sheet()

    10 second delay when showing CarBode view using modal .sheet()

    I get a 10 second delay before the CarBode view is displayed when launched from a modal .sheet(). The sheet is implemented in what appears to be the standard way with a @State variable and a button to set the boolean to launch the modal sheet.

    I've got the CarBode view in a separate struct and it all works fine when the view is eventually displayed.

    I've even tried putting the view code 'in line' in my .sheet() but either way there is always a 10 sec delay before the view is shown.

    Anyone else seen this? Any suggestions for how to get rid of the 10 sec delay? john

    opened by johncneal 3
  • 'AVMetadataObject' is only available in Mac Catalyst 14.0 or newer

    'AVMetadataObject' is only available in Mac Catalyst 14.0 or newer

    Please consider to upgrade to .iOS(.v14) https://github.com/heart/CarBode-Barcode-Scanner-For-SwiftUI/blob/23133e8a7caf11005e7b7a5724f4c3e327cf0a62/Package.swift#L9

    image
    opened by L1cardo 2
  • box around found codes?

    box around found codes?

    Thanks for creating this, it really helps me out!!

    One question, how difficult would it be to draw a rectangle around found codes? Using transformedMetadataObject on the previewLayer like explained here https://www.appcoda.com/barcode-reader-swift/ ?

    Thanks!

    opened by VoordeMensen 2
  • When  input the first character with Chinese would cause nil error

    When input the first character with Chinese would cause nil error

    Error:

    CarBode/CBBarcodeView.swift:84: Fatal error: Unexpectedly found nil while unwrapping an Optional value
    

    Code Snapshot:

    ...
        @State private var dataString = "https://google.com"
        @State private var barcodeType = CBBarcodeView.BarcodeType.qrCode
        @State private var rotate = CBBarcodeView.Orientation.up
    
    ...
     TextEditor(text: $dataString)
    ...
    CBBarcodeView(data: $dataString,
                                 barcodeType: $barcodeType,
                                 orientation: $rotate,
                                 onGenerated: { image in
                                            //log.debug("barcodeType: \(barcodeType), image.size: \(image.size)")
                                 })
    

    TextEditor display "https://google.com" and I continue to append one Chinese character from keyboard IMG_6982 截圖 2021-08-24 18 09 15

    opened by leotu 1
  • Support

    Support "CODABAR" barcode type

    Does this library support the "Codabar" type? https://en.wikipedia.org/wiki/Codabar

    I couldn't find this type on this library. Would you have the plan to support this type of barcode?

    Thank you

    opened by xperad 1
  • iPhone 14 Pro Minimum Focus Distance Scanning Issues

    iPhone 14 Pro Minimum Focus Distance Scanning Issues

    The minimum focus distance on the default camera in the iPhone 14Pro has changed and can result in barcodes that are too far away to successfully scan. This Apple Developer forum thread links to a 2021 WWDC session and sample code for addressing this issue.

    opened by MikeMilzz 3
  • Hang Risk warning from Xcode in CBScanner.swift

    Hang Risk warning from Xcode in CBScanner.swift

    Xcode warns on this line: uiView.session?.startRunning() -[AVCaptureSession startRunning] should be called from background thread. Calling it on the main thread can lead to UI unresponsiveness

    opened by Binzinz 2
  • Scanner instance persist in hierarchy even when pop VC from navigation

    Scanner instance persist in hierarchy even when pop VC from navigation

    After getting back from this screen, Scanner still scanning in background

    CBScanner(
                        supportBarcode: .constant(supportedCodeTypes()),
                        torchLightIsOn: $torchIsOn,
                        scanInterval: .constant(3.0)
                    ){
                        print("BarCodeType =",$0.type.rawValue, "Value =",$0.value)
                        self.codeString = $0.value
                        self.vm.barcodeValue = self.codeString
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                            playSound()
                            self.result = GeneralResult.success
                            self.pushed = false
                        }
                    }
                    onDraw: {
                        print("Preview View Size = \($0.cameraPreviewView.bounds)")
                        print("Barcode Corners = \($0.corners)")
                        
                        //line width
                        let lineWidth = 2
                        
                        //line color
                        let lineColor = UIColor.red
                        
                        //Fill color with opacity
                        //You also can use UIColor.clear if you don't want to draw fill color
                        let fillColor = UIColor(red: 0, green: 1, blue: 0.2, alpha: 0.4)
                        
                        //Draw box
                        $0.draw(lineWidth: CGFloat(lineWidth), lineColor: lineColor, fillColor: fillColor)
                    }
                    .border(Color.black, width: 10)
                    .cornerRadius(8)
                    .padding()
                    
                    Image("frame")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: screenWidth / 2)
                    
                    VStack {
                        HStack {
                            Spacer()
                            ZStack {
                                Circle()
                                    .fill()
                                    .frame(width: 50, height: 50)
                                    .foregroundColor(Color.gray.opacity(0.8))
                                    .onTapGesture {
                                        self.torchIsOn.toggle()
                                        userDefaults.setValue(self.torchIsOn, forKey: Defaults.isTorchOn)
                                        userDefaults.synchronize()
                                    }
                                Image(systemName: torchIsOn ? "lightbulb.fill" : "lightbulb")
                                    .resizable()
                                    .aspectRatio(contentMode: .fit)
                                    .frame(width: 35, height: 35)
                                    .foregroundColor(.white)
                                    .allowsHitTesting(false)
                            }
                            .padding([.trailing, .top], 35)
                        }
                        Spacer()
                    }
    
    opened by asar1 0
  • The code is not scannable

    The code is not scannable

    This one is generated by CarBode-Barcode-Scanner-For-SwiftUI DF1D830B-7D04-4AA8-9A85-2DB9D78CAE08

    This one is generate by myself with code 58688B43-38FD-49EE-8C3E-A61049854A3B

    func generateQRCode(from string: String) -> UIImage? {
        let data = string.data(using: String.Encoding.ascii)
    
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setValue(data, forKey: "inputMessage")
            let transform = CGAffineTransform(scaleX: 3, y: 3)
    
            if let output = filter.outputImage?.transformed(by: transform) {
                return UIImage(ciImage: output)
            }
        }
    
        return nil
    }
    

    And here is my question:

    1. The one generated by CarBode-Barcode-Scanner-For-SwiftUI looks weird, like there is some offset in every dot.
    2. And it can’t be scannable. :(

    Any idea please?

    opened by L1cardo 0
  • Xcode 13: 'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead.

    Xcode 13: 'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead.

    I am getting an error "'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead." when trying to get my app ready for iOS 15.

    Line 186 - CameraPreview.swift

    opened by CptCorporate 0
Releases(2.2.3)
Owner
Narongrit Kanhanoi
Narongrit Kanhanoi
Quotes App is quotes browsing app which is built with Quotable Free API completely in SwiftUI.

Quotes App is quotes browsing app which is built with Quotable Free API completely in SwiftUI. You can watch the whole journey of building this

Dheeraj Kumar Sharma 32 Nov 22, 2022
100-Days-of-SwiftUI - a free online course created and delivered by Paul Hudson

100-Days-of-SwiftUI DESCRIPTION 100 Days of SwiftUI is a free online course crea

null 0 Jan 9, 2022
Mercury is a free English dictionary iOS application.

Mercury - English Dictionary Mercury is a free English dictionary iOS application. Why "Mercury"? In my trip to the USA I have bought the book "Cosmic

Oleg Rybalko 2 Apr 20, 2022
Free & Open source To-Do app for iOS

Summary I tried to make a To-Do application for my education graduation project. Table of contents Technologies Features Screenshots Installation For

Enes Nurullah Kendirci 3 Oct 25, 2021
Learn how to structure your iOS App with declarative state changes using Point-Free's The Composable Architecture (TCA) library.

Learn how to structure your iOS App with declarative state changes using Point-Free's The Composable Architecture (TCA) library.

Tiago Henriques 0 Oct 2, 2022
Free Market Selection Process Test

Prueba Proceso de Seleccion Mercado Libre (Xcode Version 13.0, iOS 15) Caracteristicas de la App SearchPortrait SearchLandscape DetailPortrait DetailL

Pedro Ramos 0 Nov 22, 2021
Spontaneous - Random quotes is a free iOS app that generates random quotes

Spontaneous - Random quotes is a free iOS app that generates random quotes. It values ease-of-use just as much as the users' privacy, so there are no ads or trackers to disrupt their experience. The app currently includes more than 75000 quotes, which you can only discover randomly.

Nikola Franičević 42 Dec 17, 2022
OONI Probe is free and open source software designed to measure internet censorship and other forms of network interference.

OONI Probe iOS OONI Probe is free and open source software designed to measure internet censorship and other forms of network interference. Click here

Open Observatory of Network Interference (OONI) 59 Nov 2, 2022
OctoPod is a free open source iPhone/iPad app for OctoPrint

OctoPod OctoPod is a free open source iPhone/iPad app for OctoPrint. Build Instructions Download Xcode You will need to install Swift 5.0 and Xcode 11

Gaston Dombiak 193 Dec 30, 2022
Quotes App - quotes browsing app which is built with Quotable Free API completely in UIKit

Quotes App is quotes browsing app which is built with Quotable Free API completely in UIKit

Mohammed Sulaiman 1 Jan 7, 2023
Suicide Safety Plan is a free mobile application for suicide prevention

Suicide Safety Plan - iOS Suicide Safety Plan is a free mobile application for suicide prevention. iOS | Android | Website | Contact This app is a mob

null 13 Aug 5, 2022
A free open source iOS app for events or conferences

EventBlank iOS App I go to a lot of conferences and events and noticed that few of them have a proper iPhone app. And I can understand that - there ar

Marin Todorov 290 Nov 3, 2022
Free Educational E-Commerce Project for Motoon Mentorship Program Team.

Dokan Store An educational project for Motoon Mentorship Program team. Layers Hotlinks Documentation: Please check Wiki for more conceptual details, a

iOS Mentorship - Motoon 35 Dec 25, 2022
🖥 4K Wallpaper Generator for macOS

Kabegami Kabegami (壁紙) is a Menu Bar app for macOS that generates high-resolution wallpapers. It is inspired by, and uses the algorithm of @roytanck's

Victor 6 Dec 2, 2021
Icons generator for XCode assets project

SwiftUI-PictGen Icons generator for XCode assets project. Small project in Swift

Laurent Llexti 0 Dec 29, 2021
🎲 100% SwiftUI 2.0, classic 2048 game [SwiftUI 2.0, iOS 14.0+, iPadOS 14.0+, macOS 11.0+, Swift 5.3].

swiftui-2048 If you like the project, please give it a star ⭐ It will show the creator your appreciation and help others to discover the repo. ✍️ Abou

Astemir Eleev 174 Dec 17, 2022
A simple SwiftUI Application to demonstrate creation of UI using SwiftUI.

WatchShop_UI A simple SwiftUI Application to demonstrate creation of UI using SwiftUI. How to run the project ? Fork the project. Run the project usin

Shubham Kr. Singh 12 Apr 15, 2022
E-commerce app built in SwiftUI. Built in the course SwiftUI Masterclass in Udemy.

Touchdown-SwiftUI E-commerce app built in SwiftUI. Built in the course SwiftUI Masterclass in Udemy. Main components and concepts used: @EnvironmentOb

Jorge Martinez 5 Aug 18, 2022
A multiplatform SwiftUI project demonstrating various SwiftUI features.

WikiDemo A multiplatform SwiftUI project demonstrating various SwiftUI features, including creating a master-detail interface. It's a multiplatform ve

Swift Dev Journal 6 Oct 17, 2022