Simple QRCode reader in Swift

Overview

QRCodeReader.swift

Supported Platforms Version

QRCodeReader.swift is a simple code reader (initially only QRCode) for iOS in Swift. It is based on the AVFoundation framework from Apple in order to replace ZXing or ZBar for iOS 8.0 and over. It can decodes these format types.

It provides a default view controller to display the camera view with the scan area overlay and it also provides a button to switch between the front and the back cameras.

QRCodeReader.swift screenshot

RequirementsUsageInstallationContactLicense

Requirements

  • iOS 8.0+
  • Xcode 10.0+
  • Swift 5.0+

Usage

In iOS10+, you will need first to reasoning about the camera use. For that you'll need to add the Privacy - Camera Usage Description (NSCameraUsageDescription) field in your Info.plist:

privacy - camera usage description

Then just follow these steps:

  • Add delegate QRCodeReaderViewControllerDelegate
  • Add import AVFoundation
  • Add import QRCodeReader
  • The QRCodeReaderViewControllerDelegate implementations is:
// Good practice: create the reader lazily to avoid cpu overload during the
// initialization and each time we need to scan a QRCode
lazy var readerVC: QRCodeReaderViewController = {
    let builder = QRCodeReaderViewControllerBuilder {
        $0.reader = QRCodeReader(metadataObjectTypes: [.qr], captureDevicePosition: .back)
        
        // Configure the view controller (optional)
        $0.showTorchButton        = false
        $0.showSwitchCameraButton = false
        $0.showCancelButton       = false
        $0.showOverlayView        = true
        $0.rectOfInterest         = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6)
    }
    
    return QRCodeReaderViewController(builder: builder)
}()

@IBAction func scanAction(_ sender: AnyObject) {
  // Retrieve the QRCode content
  // By using the delegate pattern
  readerVC.delegate = self

  // Or by using the closure pattern
  readerVC.completionBlock = { (result: QRCodeReaderResult?) in
    print(result)
  }

  // Presents the readerVC as modal form sheet
  readerVC.modalPresentationStyle = .formSheet
 
  present(readerVC, animated: true, completion: nil)
}

// MARK: - QRCodeReaderViewController Delegate Methods

func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
  reader.stopScanning()

  dismiss(animated: true, completion: nil)
}

//This is an optional delegate method, that allows you to be notified when the user switches the cameraName
//By pressing on the switch camera button
func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) {
    if let cameraName = newCaptureDevice.device.localizedName {
      print("Switching capture to: \(cameraName)")
    }
}

func readerDidCancel(_ reader: QRCodeReaderViewController) {
  reader.stopScanning()

  dismiss(animated: true, completion: nil)
}

Note that you should check whether the device supports the reader library by using the QRCodeReader.isAvailable() or the QRCodeReader.supportsMetadataObjectTypes() methods.

Interface customization

You can create your own interface to scan your 1D/2D codes by using the QRCodeReaderDisplayable protocol and the readerView property in the QRCodeReaderViewControllerBuilder:

class YourCustomView: UIView, QRCodeReaderDisplayable {
  let cameraView: UIView            = UIView()
  let cancelButton: UIButton?       = UIButton()
  let switchCameraButton: UIButton? = SwitchCameraButton()
  let toggleTorchButton: UIButton?  = ToggleTorchButton()
  var overlayView: UIView?          = UIView()

  func setupComponents(with builder: QRCodeReaderViewControllerBuilder) {
    // addSubviews
    // setup constraints
    // etc.
  }
}

lazy var reader: QRCodeReaderViewController = {
    let builder = QRCodeReaderViewControllerBuilder {
      let readerView = QRCodeReaderContainer(displayable: YourCustomView())

      $0.readerView = readerView
    }
    
    return QRCodeReaderViewController(builder: builder)
  }()

Installation

The recommended approach to use QRCodeReaderViewController in your project is using the CocoaPods package manager, as it provides flexible dependency management and dead simple installation.

CocoaPods

Install CocoaPods if not already available:

$ [sudo] gem install cocoapods
$ pod setup

Go to the directory of your Xcode project, and Create and Edit your Podfile and add QRCodeReader.swift to your corresponding TargetName:

$ cd /path/to/MyProject
$ touch Podfile
$ edit Podfile
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

target 'TargetName' do
    pod 'QRCodeReader.swift', '~> 10.1.0'
end

Install into your project:

$ pod install

Open your project in Xcode from the .xcworkspace file (not the usual project file):

$ open MyProject.xcworkspace

You can now import QRCodeReader framework into your files.

Carthage

Carthage is a decentralized dependency manager that automates the process of adding frameworks to your Cocoa application.

You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate QRCodeReader into your Xcode project using Carthage, specify it in your Cartfile file:

github "yannickl/QRCodeReader.swift" >= 10.1.0

Swift Package Manager

You can use The Swift Package Manager to install QRCodeReader.swift by adding the proper description to your Package.swift file:

import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/yannickl/QRCodeReader.swift.git", versions: "10.1.0" ..< Version.max)
    ]
)

Note that the Swift Package Manager is still in early design and development, for more information checkout its GitHub Page.

Manually

Download the project and copy the QRCodeReader folder into your project to use it in.

Contact

Yannick Loriot

License (MIT)

Copyright (c) 2014-present - Yannick Loriot

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.

Comments
  • Camera is not display, but scan is work, case of custom interface

    Camera is not display, but scan is work, case of custom interface

    update to swift 4 version before is work fine

    but update to swift 4 version after is not work

    how can i fix it?

    source code here https://gist.github.com/purplecofe/c9ea540760a990bf5aeec62b4507bee8

    thanks for your help

    opened by purplecofe 26
  • Your Example not run in xcode 8 official

    Your Example not run in xcode 8 official

    dyld: Symbol not found: _AVCaptureDeviceTypeBuiltInWideAngleCamera Referenced from: /var/containers/Bundle/Application/DDAF584C-7F2E-4C27-8AA6-8E162CFCAA91/QRCodeReader.swift.app/QRCodeReader.swift Expected in: /System/Library/Frameworks/AVFoundation.framework/AVFoundation in /var/containers/Bundle/Application/DDAF584C-7F2E-4C27-8AA6-8E162CFCAA91/QRCodeReader.swift.app/QRCodeReader.swift (lldb) Thread 1 : Signal SIGABRT i run in iphone5C

    opened by stephenvux 16
  • Takes time in scanning

    Takes time in scanning

    I used the same kind of code in my application. It takes some time in reading the code. What could be the reason and its solution. Do I need to use ZXing kind of third party library for this?

    opened by sumitjain7 15
  • Reader continues scanning even after stopping

    Reader continues scanning even after stopping

    Here's how I get result from the reader:

    func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
        reader.stopScanning()
    
        // my code goes here
    }
    

    However, I'm getting 2 calls of the method above in a row. It's because stopScanning method stops scanning asynchronously.

      public func stopScanning() {
        if session.isRunning {
          sessionQueue.async {
            self.session.stopRunning()
          }
        }
      }
    

    What was the reason to make it async? Is it safe to remove async from that method?

    opened by agordeev 14
  • Gab in the middle off the tabbar after scanning a ticket

    Gab in the middle off the tabbar after scanning a ticket

    Hi

    i getting a gab in the middle off my tabbar after succesfull scanning a Ticket, if i press on the screen and wait for a few second i get my tabbar button back but with the text notification instead of "scanner"

    Thanxz

    opened by tpcmedia777 9
  • Setting

    Setting "reader" property after Xcode 8.3 (Swift 3.1) update

    screen shot 2017-03-28 at 3 17 57 pm

    lazy var initialization from the example should be replaced with this code, in order to avoid error

    lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode], captureDevicePosition: .back) } return QRCodeReaderViewController(builder: builder) } ()

    opened by petkotodorov 7
  • swift 3 incompatible

    swift 3 incompatible

    "The target “QRCodeReader.swift” contains source code developed with an earlier version of Swift.

    Choose “Convert” to update the source code in this target to the latest SDKs. You will be given the choice to use Swift 2.3 syntax or update to Swift 3.

    This action can be performed later using “Convert to Current Swift Syntax” in the Edit menu." for pod 'QRCodeReader.swift', '~> 7.2.0'

    opened by maslyankov 7
  • I am trying to use CocoaPods

    I am trying to use CocoaPods

    I am trying to use CocoaPods for the first time. First impression is VERY GOOD.

    But it gives some errors.

    Warning: no rule to process file '/Users/xxxx/x/Pods/QRCodeReader.swift/README.md' of type net.daringfireball.markdown for architecture i386

    XCODE thinks README.md should be compiled but he does not know how to. Maybe it is caused by CocoaPads, but I think it is better to mention in the manual at "Installation" area to remove README.md from "Build Phases->Compile Sources" in the project file. Unless this problem is happening only on me.

    Hiro

    opened by gambaldia 7
  • Unable to compile project from QR Reader pod?

    Unable to compile project from QR Reader pod?

    Hi,

    I installed the pod and ran the workspace but the project wont compile. I didn't even use any code yet related to it.

    Attached a couple of screenshots that shows the issues:

    screen shot 2017-10-28 at 20 16 48 screen shot 2017-10-28 at 20 19 33

    Thanks!

    opened by taltime 6
  • Options to

    Options to "Hide rectangular guide" view or "Zoom"

    Hi, First of all, thanks for great open source! =)

    I'm considering using QRCodeReader.swift, but I thought it would be better if I have options to hide rectangular guide view (ReaderOverlayView object) or zoom. The option to hide rectangular guide view doesn't look so complicated though the structure seems to be changed. The options to support zooming feature is simpler, but IMO it should be checked why no apps support zooming feature. (I tried to add zooming feature, and it just works well. I thought about it, but don't have any idea about the reason not to support it so far.)

    I tried to test about these, so I could make pull requests but I'd like to know your idea about these first. Thanks for reading my issue!

    Regards,

    opened by RickyPark 6
  • Type of expression is ambiguous without more context

    Type of expression is ambiguous without more context

    Build Failed !!! Hi guy , in QRCodeReader.swift -> return .defaultDevice(withDeviceType: .builtInWideAngleCamera, mediaType: AVMediaTypeVideo, position: .front) failed !!!

    opened by stephenvxx 6
  • Crash on metadataOutput.availableMetadataObjectTypes in QRCodeReader

    Crash on metadataOutput.availableMetadataObjectTypes in QRCodeReader

    Fatal Exception: NSGenericException

    • 0 CoreFoundation 0x990fc __exceptionPreprocess
    • 1 libobjc.A.dylib 0x15d64 objc_exception_throw
    • 2 CoreFoundation 0x16f190 -[__NSSingleObjectEnumerator init]
    • 3 AVFCapture 0x145f4 -[AVCaptureMetadataOutput availableMetadataObjectTypes]
    • 4 AVFCapture 0x142c0 -[AVCaptureMetadataOutput setMetadataObjectTypes:]
    • 5 QRCodeReader 0x6154 (Missing UUID d7c36d3fb68f3da3ab70252c154be0b3)
    • 6 QRCodeReader 0xa43c (Missing UUID d7c36d3fb68f3da3ab70252c154be0b3)
    • 7 QRCodeReader 0x61e0 (Missing UUID d7c36d3fb68f3da3ab70252c154be0b3)
    • 8 libdispatch.dylib 0x2924 _dispatch_call_block_and_release
    • 9 libdispatch.dylib 0x4670 _dispatch_client_callout
    • 10 libdispatch.dylib 0xbdf4 _dispatch_lane_serial_drain
    • 11 libdispatch.dylib 0xc968 _dispatch_lane_invoke
    • 12 libdispatch.dylib 0x171b8 _dispatch_workloop_worker_thread
    • 13 libsystem_pthread.dylib 0x10f4 _pthread_wqthread
    • 14 libsystem_pthread.dylib 0xe94 start_wqthread

    Fatal Exception: NSGenericException *** Collection <__NSArrayM: 0x28121d710> was mutated while being enumerated.

    Using 10.1.0

    opened by YoavGro 2
  • Reshape OverlayView to square

    Reshape OverlayView to square

    hi, i try to play arround with rectOfInterest to make the shape of OverlayView to square shape instead of rectangle but seems does not work, could you help me, how to achive this, seems im quite new to ios development, Thanks in advanve.

    opened by syafieqq 0
  • Fatal Exception: NSInvalidArgumentException

    Fatal Exception: NSInvalidArgumentException

    Crash was recorded by Crashlytics. Unfortunately I don`t know how to reproduce this crash. image we use next method to check if we can start scanning, and inside it crash occurs image

    opened by BGLv 0
  • Crash in configureDefaultComponents on previewLayer

    Crash in configureDefaultComponents on previewLayer

    Hi,

    I have a Testflight crash with less information for a crash within class QRCodeReader. The crash occurs when assigning videoGravity. In function configureDefaultComponents(withCaptureDevicePosition: AVCaptureDevice.Position):

    Line 170: previewLayer.videoGravity = .resizeAspectFill

    I do not know why or what prerequisites it needs to result in this Crash. Seems like previewLayer is not initialized.

    • Device is: iPad Air (3th Gen)
    • iOS Version: 14.0.1

    Thanks for your support. Christian

    opened by fruitwingscmueller 0
  • Make QRCodeReaderViewController an open class to allow subclassing

    Make QRCodeReaderViewController an open class to allow subclassing

    For my case I need to hide the navigation bar when QRCodeReaderViewController is pushed in the navigation controller. This cannot be done without overriding the functions viewWillAppear and viewWillDisappear of UIViewController. Other tweaks could be also not be possible without overriding the class.

    So a simple change in the source code can solve these problems easily, just make the public class QRCodeReaderViewController open.

    opened by nickbit 0
Owner
Yannick Loriot
iOS developer and nodejs addict. Open-source lover and technology enthusiast.
Yannick Loriot
: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

HyperRedink 1.6k Jan 3, 2023
Simple motion detector for ⌚️ (watchOS) shake gesture.

WatchShaker Simple motion detector for ⌚️ (watchOS) shake gesture. WatchShaker is a watchOS helper to get your ⌚️ shake movements Requirements watchOS

Ezequiel França 200 Dec 22, 2022
Just simple template - example how to use haptics in iOS Development

Haptics Just simple template - example how to use haptics in iOS Development imp

Alexander Ryakhin 1 Jan 31, 2022
A better way to operate QR Code in Swift, support iOS, macOS, watchOS and tvOS.

EFQRCode is a lightweight, pure-Swift library for generating stylized QRCode images with watermark or icon, and for recognizing QRCode from images, in

EFPrefix 4.3k Jan 2, 2023
Instagram-like photo browser and a camera feature with a few line of code in Swift.

NOTE: This project is no longer maintained. We highly recommend YPImagePicker. Fusuma Fusuma is a Swift library that provides an Instagram-like photo

Yuta Akizuki 2.4k Dec 31, 2022
⬆️ Rad Media Capture in Swift

NextLevel is a Swift camera system designed for easy integration, customized media capture, and image streaming in iOS. Integration can optionally lev

NextLevel 2k Dec 30, 2022
Demo using Terminal.Gui with Llama Swift

Hola! This repo is a demo which shows the use of Llama Swift with Terminal.Gui. Llama is my exploratory project to compile "other languages" for .NET

Eric Sink 6 May 22, 2021
Swift library to easily check the current device and some more info about it.

Usage To run the example project, clone the repo, and run pod install from the Example directory first. let device = Deviice.current device is a Devi

Andrea Mario Lufino 56 Nov 3, 2022
Light weight tool for detecting the current device and screen size written in swift.

Device detect the current  device model and screen size. Installation CocoaPods Device is available through CocoaPods. To install it, simply add the

Lucas Ortis 1.5k Dec 28, 2022
Simple QRCode reader in Swift

QRCodeReader.swift is a simple code reader (initially only QRCode) for iOS in Swift. It is based on the AVFoundation framework from Apple in order to

Yannick Loriot 1.3k Dec 22, 2022
Simple QRCode reader in Swift

QRCodeReader.swift is a simple code reader (initially only QRCode) for iOS in Swift. It is based on the AVFoundation framework from Apple in order to

Yannick Loriot 1.3k Jan 5, 2023
A QRCode generator written in Swift.

QRCode ?? A QRCode generator written in Swift. Overview Create a new QRCode representing a URL, a string or arbitrary data. The following examples all

Alexander Schuch 730 Dec 12, 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

Dineshkumar Kandasamy 3 Jun 22, 2022
Simple RSS reader app written in Swift

Feeds4U Simple RSS reader app written in Swift. Contributions All PRs should be directed to 'develop' branch. Important Note Use code as you wish. Don

Evgeny Karkan 62 Nov 23, 2022
GraphQL-GitHub-Reader - Simple sample project that demonstrates how to connect with GitHub's API using GraphQL + Apollo

GHPViewer A beatiful way to see your GitHub Profile Installation The project is splitted in two folders: GHPViewer: Contains the iOS Application relat

Andrés Pesate 1 Jan 2, 2022
A Hacker News reader in Swift

SwiftHN A Hacker News reader in Swift using the best features of both the language and iOS 8 latest API (well, that's the end goal) SwiftHN is now ava

Thomas Ricouard 1.7k Dec 24, 2022
1D and 2D barcodes reader and generators for iOS 8 with delightful controls. Now Swift.

RSBarcodes, now in Swift. RSBarcodes allows you to read 1D and 2D barcodes using the metadata scanning capabilities introduced with iOS 7 and generate

R0CKSTAR 685 Jan 2, 2023
RSS reader specific for Swift and SwiftUI based feeds.

Swift News Jam! Getting Started The idea behind this app was to provide the SwiftUI community a single app to curate the numerous RSS feeds that have

hallux 13 Nov 29, 2022
📚 A Swift ePub reader and parser framework for iOS.

FolioReaderKit is an ePub reader and parser framework for iOS written in Swift. Features ePub 2 and ePub 3 support Custom Fonts Custom Text Size Text

FolioReader 2.5k Jan 8, 2023
A Hacker News reader iOS app written in Swift.

HackerNews A Hacker News reader iOS app written in Swift. Features View "top", "newest", and "show" posts from Hacker News. Read posts using the SFSaf

Amit Burstein 1.3k Dec 21, 2022