• Stars
    star
    930
  • Rank 49,124 (Top 1.0 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 5 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A SwiftUI view that is able to scan barcodes, QR codes, and more, and send back what was found.

CodeScanner

Twitter: @twostraws

CodeScanner is a SwiftUI framework that makes it easy to scan codes such as QR codes and barcodes. It provides a view struct, CodeScannerView, that can be shown inside a sheet so that all scanning occurs in one place.

Basic usage

You should create an instance of CodeScannerView with at least two parameters: an array of the types to scan for, and a closure that will be called when a result is ready.

Your completion closure must accept a Result<ScanResult, ScanError>, where the success case is the code string and type that was found. For example, if you asked to scan for QR codes and bar codes, you might be told that a QR code containing the email address [email protected] was found.

If things go wrong, your result will contain a ScanError set to one of these three cases:

  • badInput, if the camera cannot be accessed
  • badOutput, if the camera is not capable of detecting codes
  • initError, if initialization failed.

Important: iOS requires you to add the "Privacy - Camera Usage Description" key to your Info.plist file, providing a reason for why you want to access the camera.

Customization options

You can provide a variety of extra customization options to CodeScannerView in its initializer:

  • scanMode can be .once to scan a single code, .oncePerCode to scan many codes but only trigger finding each unique code once, and .continuous will keep finding codes until you dismiss the scanner. Default: .once.
  • scanInterval controls how fast individual codes should be scanned when running in .continuous scan mode.
  • showViewfinder determines whether to show a box-like viewfinder over the UI. Default: false.
  • simulatedData allows you to provide some test data to use in Simulator, when real scanning isnโ€™t available. Default: an empty string.
  • shouldVibrateOnSuccess allows you to determine whether device should vibrate when a code is found. Default: true.
  • videoCaptureDevice allows you to choose different capture device that is most suitable for code to scan.

If you want to add UI customization, such as a dedicated Cancel button, you should wrap your CodeScannerView instance in a NavigationView and use a toolbar() modifier to add whatever buttons you want.

Examples

Here's some example code to create a QR code-scanning view that prints the code that was found or any error. If it's used in the simulator it will return a name, because that's provided as the simulated data:

CodeScannerView(codeTypes: [.qr], simulatedData: "Paul Hudson") { response in                    
    switch response {
    case .success(let result):
        print("Found code: \(result.string)")
    case .failure(let error):
        print(error.localizedDescription)
    }
}

Your completion closure is probably where you want to dismiss the CodeScannerView.

Here's an example on how to present the QR code-scanning view as a sheet and how the scanned barcode can be passed to the next view in a NavigationView:

struct QRCodeScannerExampleView: View {
    @State private var isPresentingScanner = false
    @State private var scannedCode: String?

    var body: some View {
        VStack(spacing: 10) {
            if let code = scannedCode {
                NavigationLink("Next page", destination: NextView(scannedCode: code), isActive: .constant(true)).hidden()
            }

            Button("Scan Code") {
                isPresentingScanner = true
            }

            Text("Scan a QR code to begin")
        }
        .sheet(isPresented: $isPresentingScanner) {
            CodeScannerView(codeTypes: [.qr]) { response in
                if case let .success(result) = response {
                    scannedCode = result.string
                    isPresentingScanner = false
                }
            }
        }
    }
}

Scanning small QR codes

Scanning small QR code on devices with dual or tripple cameras has to be adjusted because of minimum focus distance built in these cameras. To have the best possible focus on the code we scan it is needed to choose the most suitable camera and apply recommended zoom factor.

Example for scanning 20x20mm QR codes.

CodeScannerView(codeTypes: [.qr], videoCaptureDevice: AVCaptureDevice.zoomedCameraForQRCode(withMinimumCodeSize: 20)) { response in                    
    switch response {
    case .success(let result):
        print("Found code: \(result.string)")
    case .failure(let error):
        print(error.localizedDescription)
    }
}

Credits

CodeScanner was made by Paul Hudson, who writes free Swift tutorials over at Hacking with Swift. Itโ€™s available under the MIT license, which permits commercial use, modification, distribution, and private use.

License

MIT License.

Copyright (c) 2021 Paul Hudson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

ControlRoom

A macOS app to control the Xcode Simulator.
Swift
5,610
star
2

HackingWithSwift

The project source code for hackingwithswift.com
Swift
5,607
star
3

Unwrap

Learn Swift interactively on your iPhone.
Swift
2,265
star
4

Inferno

Metal shaders for SwiftUI.
Metal
2,238
star
5

wwdc

WWDC Community: Learning and sharing together
1,972
star
6

Sitrep

A source code analyzer for Swift projects.
Swift
1,294
star
7

Vortex

High-performance particle effects for SwiftUI.
Swift
910
star
8

whats-new-in-swift-5-0

An Xcode playground that demonstrates the new features introduced in Swift 5.0.
Swift
731
star
9

Ignite

A static site generator for Swift developers.
Swift
707
star
10

Sourceful

A syntax highlighting source editor for iOS and macOS using UITextView and NSTextView.
Swift
683
star
11

ShaderKit

A library of fragment shaders you can use in any SpriteKit project.
GLSL
655
star
12

SwiftOnSundays

Completed projects for the Swift on Sundays livestream series
Swift
635
star
13

simple-swiftui

A collection of small SwiftUI sample projects.
Swift
634
star
14

Brisk

A proof of concept scripting library for Swift
Swift
503
star
15

SwiftGD

A simple Swift wrapper for libgd
Swift
448
star
16

VisualEffects

A semi-official SwiftUI wrapper for UIVisualEffectView
Swift
354
star
17

whats-new-in-swift-5-5

Swift
312
star
18

Subsonic

A small library that makes it easier to play audio with SwiftUI.
Swift
308
star
19

swiftui-changelog

A repository to track changes in the SwiftUI generated interface.
Swift
258
star
20

macOS

The project source code for Hacking with macOS.
Swift
239
star
21

whats-new-in-swift-4-1

An Xcode playground that demonstrates the new features introduced in Swift 4.1.
Swift
221
star
22

TapStore

Code for a YouTube video on UICollectionView.
Swift
162
star
23

NeumorphismSwiftUI

Code to accompany my article on this topic.
Swift
139
star
24

whats-new-in-swift-5-3

An Xcode playground that demonstrates the new features introduced in Swift 5.3.
Swift
127
star
25

iDine

Source code for my SwiftUI introduction tutorial.
Swift
126
star
26

whats-new-in-swift-5-1

An Xcode playground that demonstrates the new features introduced in Swift 5.1.
Swift
121
star
27

whats-new-in-swift-5-8

Swift
120
star
28

whats-new-in-swift-4-2

An Xcode playground that demonstrates the new features introduced in Swift 4.2.
Swift
116
star
29

Sharpshooter

A tiny Xcode extension for people who debug with print().
Swift
115
star
30

whats-new-in-swift-5-7

Swift
115
star
31

100

A list of solutions for the 100 Days of Swift challenge
113
star
32

whats-new-in-swift-5-4

Swift
100
star
33

HWSTranslation

A community project to translate free Swift tutorials
99
star
34

watchOS

The project source code for Hacking with watchOS.
Swift
98
star
35

vapor-clean

A Vapor 3 template with no additional cruft.
Swift
97
star
36

whats-new-in-swift-5-2

An Xcode playground that demonstrates the new features introduced in Swift 5.2.
Swift
95
star
37

AppleTime

A tiny program to use 9:41 in your iOS simulators.
Swift
92
star
38

whats-new-in-swift-5-6

Swift
91
star
39

HackingWithReact

The project source code for hackingwithreact.com
JavaScript
72
star
40

iTour

Source code for my SwiftData introduction tutorial.
Swift
67
star
41

Placeholder

Place temporary images in your iOS app showing the size of the available space.
Swift
56
star
42

Trekr

Companion code for a YouTube livestream.
Swift
54
star
43

FaceFacts

Source code for my SwiftUI + SwiftData tutorial.
Swift
51
star
44

Markdown

A small and fast Markdown parser library for Swift.
Swift
44
star
45

SwiftOverCoffee

Links to solutions for Swift over Coffee challenges
39
star
46

SwiftSlug

A simple package to convert strings to URL slugs.
Swift
38
star
47

Playmaker

Create Xcode playgrounds from Markdown.
Swift
35
star
48

IgniteStarter

A starter template for the Ignite static site generator.
Swift
33
star
49

tvOS

The project source code for Hacking with tvOS.
Swift
30
star
50

IgniteSamples

Sample code for the Ignite static site generator.
Swift
23
star
51

kitura-vs-vapor

A side-by-side comparison of two popular server-side Swift frameworks.
Swift
22
star
52

Cgd

A small Swift package exposing libgd to Swift.
Swift
20
star
53

super-powered-string-interpolation

Swift
18
star
54

SamplePackage

A test package for Swift Package Manager.
Swift
18
star
55

betterbeeb

Better Beeb
Swift
16
star
56

HowToInstrument

A deliberately broken app to help demonstrate Instruments.
Swift
14
star
57

BioBlitz

Code created during my birthday livestream 2022.
Swift
14
star
58

Paraphrase

A trivial app for storing and viewing famous quotes
Swift
12
star
59

DadJokes

The code from my try! Swift NYC 2019 talk.
Swift
10
star
60

homebrew-brew

Homebrew formulae.
Ruby
8
star
61

whats-new-in-swift-6-0

Swift
6
star
62

Paraphrase-Improved

Swift
4
star
63

switcharoo

Switcharoo
Python
4
star
64

easyoc

EasyOC
Objective-C
4
star
65

whats-new-in-swift-5-10

Swift
1
star