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
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
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
: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 Dec 30, 2022
🔍BarcodeScanner – simple & easy application that helps you to scan both EAN8 and EAN13 barcodes.

?? Simple & easy application that helps you to scan both EAN8 and EAN13 barcodes.

Tamerlan Satualdypov 16 Apr 22, 2022
A simple Safari web extension that displays a QR code for the webpage in focus.

QR Pop ?? QR Pop is a simple iOS & MacOS app and Safari extension built to make displaying QR codes easy. The Safari Extension is inspired by the quic

Shawn 9 Dec 11, 2022
Simple application for creating QR code with a background

BeautifyQR Импортирует исходный QR-код из галереи Накладывает его на выбранную картинку с фоном Полученную картинку можно вынести виджетом на домашний

Dmitry Demianov 1 Nov 28, 2021
QR code detector. Simple usage, you can get recognition results via delegate or callback.

SPQRCode QR code detector. Simple usage, you can get recognition results via delegate or callback. Installation Swift Package Manager CocoaPods Manual

Sparrow Code 58 Jan 6, 2023
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

Krystal Zhang 0 Jan 1, 2023
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 Dec 29, 2022
With QRKit you can easily create QR or bar codes in Swift.

With QRKit you can easily create QR or bar codes in Swift. You can choose foreground and background colors. The QR code you get simply as UIImage.

Technikabo 1 Jun 11, 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 Dec 29, 2022
DGQR - A lightweight, pure-Swift library for rendering qr

DGQR DGQR is a lightweight, pure-Swift library for rendering qr. It provides you

donggyu 2 Jun 10, 2022
BarcodeScannerSwift - Barcode Scanner Built With Swift

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

Cuma Haznedar 2 Dec 31, 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