1D and 2D barcodes reader and generators for iOS 8 with delightful controls. Now Swift.

Overview

RSBarcodes, now in Swift.

Build Status codecov.io Carthage compatible


RSBarcodes allows you to read 1D and 2D barcodes using the metadata scanning capabilities introduced with iOS 7 and generate the same set of barcode images for displaying and sharing. Now implemented in Swift.

TODO

Generators

  • Code39
  • Code39Mod43
  • ExtendedCode39
  • Code93
  • Code128
  • UPCE
  • EAN FAMILIY (EAN8 EAN13 ISBN13 ISSN13)
  • ITF14
  • Interleaved2of5
  • DataMatrix
  • PDF417
  • QR
  • Aztec
  • Views

Reader

  • Views
  • ReaderController

Installation

Swift Package Manager

To add a package dependency to your Xcode project, select File > Swift Packages > Add Package Dependency and enter https://github.com/yeahdongcn/RSBarcodes_Swift to the text field.

CocoaPods

Simply add the following lines to your Podfile:

# required by Cocoapods 0.36.0.rc.1 for Swift Pods
use_frameworks!

pod 'RSBarcodes_Swift', '~> 5.1.1'

You will need to import RSBarcodes_Swift manually in the ViewController file after creating the file using wizard.

(CocoaPods v0.36 or later required. See this blog post for details.)

Carthage

Simply add the following line to your Cartfile:

github "yeahdongcn/RSBarcodes_Swift" >= 5.1.1

You will need to import RSBarcodes_Swift manually in the ViewController file after creating the file using wizard.

Swift Package Manager (required Xcode 11)

  1. Select File > Swift Packages > Add Package Dependency. Enter https://github.com/yeahdongcn/RSBarcodes_Swift in the "Choose Package Repository" dialog.
  2. In the next page, specify the version resolving rule as "Up to Next Major" with the latest version.
  3. After Xcode checking out the source and resolving the version, you can choose the "RSBarcodes_Swift" library and add it to your app target.

Manual

  1. Add RSBarcodes_Swift as a submodule by opening the Terminal, cd-ing into your top-level project directory, and entering the command git submodule add https://github.com/yeahdongcn/RSBarcodes_Swift.git
  2. Open the RSBarcodes_Swift folder, and drag RSBarcodes.xcodeproj into the file navigator of your app project.
  3. In Xcode, navigate to the target configuration window by clicking on the blue project icon, and select the application target under the "Targets" heading in the sidebar.
  4. Ensure that the deployment target of RSBarcodes.framework matches that of the application target.
  5. In the tab bar at the top of that window, open the "Build Phases" panel.
  6. Expand the "Target Dependencies" group, and add RSBarcodes.framework.
  7. Click on the + button at the top left of the panel and select "New Copy Files Phase". Rename this new phase to "Copy Frameworks", set the "Destination" to "Frameworks", and add RSBarcodes.framework.
  8. Need to import RSBarcodes manually in the ViewController file after creating the file using wizard.

Usage

How to Use Generator and How to Use Reader

Generators

First, import the following frameworks:

import RSBarcodes_Swift
import AVFoundation

Then, use the generator to generate a barcode. For example:

RSUnifiedCodeGenerator.shared.generateCode("2166529V", machineReadableCodeObjectType: AVMetadataObjectTypeCode39Code)

It will generate a UIImage instance if the 2166529V is a valid code39 string. For AVMetadataObjectTypeCode128Code, you can change useBuiltInCode128Generator to false to use my implementation (AutoTable for code128).

P.S. There are 4 tables for encoding a string to code128, TableA, TableB, TableC and TableAuto; the TableAuto is always the best choice, but if one has specific requirements, try this:

RSCode128Generator(codeTable: .A).generateCode("123456", machineReadableCodeObjectType: AVMetadataObjectTypeCode128Code)

Example of these simple calls can be found in the test project.

Reader

The following are steps to get the barcode reader working:

  1. File -> New -> File
  2. Under iOS click source and make sure Cocoa Touch Class is selected and hit Next.
  3. Call the name of the class whatever you want but I will refer to it as ScanViewController from now on.
  4. Make it a subclass of RSCodeReaderViewController and ensure the language is Swift and hit Next and then Create
  5. Open your storyboard and drag a UIViewController onto it.
  6. Show the identity inspect and under custom class select ScanViewController
  7. The focus mark layer and corners layer are already there working for you. There are two handlers: one for the single tap on the screen along with the focus mark and one detected objects handler, which all detected will come to you. Now in the ScanViewController.swift file add the following code into the viewDidLoad() or some place more suitable for you:
override func viewDidLoad() {
    super.viewDidLoad()

    self.focusMarkLayer.strokeColor = UIColor.red.cgColor

    self.cornersLayer.strokeColor = UIColor.yellow.cgColor

    self.tapHandler = { point in
        print(point)
    }

    self.barcodesHandler = { barcodes in
        for barcode in barcodes {
            print("Barcode found: type=" + barcode.type + " value=" + barcode.stringValue)
        }
    }
}

If you want to ignore some code types (for example, AVMetadataObjectTypeQRCode), add the following lines:

let types = NSMutableArray(array: self.output.availableMetadataObjectTypes)
types.remove(AVMetadataObjectTypeQRCode)
self.output.metadataObjectTypes = NSArray(array: types)

Validator

To validate codes:

let isValid = RSUnifiedCodeValidator.shared.isValid(code, machineReadableCodeObjectType: AVMetadataObjectTypeEAN13Code)

Image helpers

Use RSAbstractCodeGenerator.resizeImage(source: UIImage, scale: CGFloat) to scale the generated image.

Use RSAbstractCodeGenerator.resizeImage(source: UIImage, targetSize: CGSize, contentMode: UIViewContentMode) to fill/fit the bounds of something to the best capability and don't necessarily know what scale is too much to fill/fit, or if the UIImageView itself is flexible.

Miscellaneous

The Swift Programming Language 中文版

Online version generated using GitBook

License

The MIT License (MIT)

Copyright (c) 2012-2014 P.D.Q.

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
  • Performing Action When a Barcode Is Scanned

    Performing Action When a Barcode Is Scanned

    I am building an app that utilizes QR code scanning. What I am trying to do in my ScanViewController is to scan a QR code, validate what was scanned, and then segue with the scanned data. Currently, when a QR code is detected, my UI freezes, and shortly after I get an error and memory dump:

    'NSInternalInconsistencyException', reason: 'Only run on the main thread!'.

    Maybe, this isn't the right place to validate the QR code or isn't the right place to segue, but if not, I'm wondering where the validation and segue should take place. My only other requirement is that the validation only occurs when a QR code is detected, which I believe to happen when captureOutput() is called in RSCodeReaderViewController.

    class ScanViewController: RSCodeReaderViewController{
        // Class Variables
        var finalObject: IBuiltCode?
        let ObjectHelper = ObjectBuilder() // Service to validate and build valid scanned objects
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            self.focusMarkLayer.strokeColor = UIColor.redColor().CGColor
            self.cornersLayer.strokeColor = UIColor.yellowColor().CGColor
    
            self.tapHandler = { point in
                println(point)
            }
    
            self.barcodesHandler = { barcodes in
                for barcode in barcodes {
                    println("Barcode found: type=" + barcode.type + " value=" + barcode.stringValue)
                    // returns nil if invalid (can provide validateAndBuild func code if necessary)
                    var builtObject = self.ObjectHelper.validateAndBuild(barcode,
                          scannedData: barcode.stringValue)
                    if builtObject != nil{
                        println("Good object.")
                        self.performQR()
                    }
                }
            }
        }
    
        func performQR(){
            performSegueWithIdentifier("toQR", sender: self)
        }
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if (segue.identifier == "toQR"){
                let QRVC: QRViewController = segue.destinationViewController as! QRViewController
                QRVC.receivedObject = finalObject as? QRObject
            }
        }
    }
    
    opened by drewantonich 11
  • Target Size and QR Tags colorisation support

    Target Size and QR Tags colorisation support

    Target size was added to the interface in order to scale the resulting image before it is converted into an UIImage. Scaling a UIImage results in pixellation, so the change is done on the CIImage.

    Setting stroke and fill colours did not apply to CIFilter generated code tags. This is now supported.

    The code changes are backwards compatible.

    opened by mjrehder 10
  • Xcode does not recognize the class when creating a new file

    Xcode does not recognize the class when creating a new file

    Hi

    Installed using Cocoapods, went through the reader process and when I get to the point where I need to choose a subclass for ScanViewController, RSCodeReaderViewController isn't there.

    However, if I hard code RSCodeReaderViewController as a subclass, and cmd+click on RSCodeReaderViewController in the file, I successfully get directed to its implementation.

    Nonetheless the ScanViewController file throws multiple errors, the first one indicating "Use of undeclared type 'RSCodeReaderViewController'".

    Any ideas?

    opened by cloud-tribal 9
  • QRCode appears small

    QRCode appears small

    the QRCode appears very small...

    let image: UIImage? = gen.generateCode(contents, machineReadableCodeObjectType: AVMetadataObjectTypeQRCode) if let image = image { self.barcodeView.image = RSAbstractCodeGenerator.resizeImage(image, scale: 1.0) }

    opened by cafuni 8
  • XCode 12 Beta 6, compiler error

    XCode 12 Beta 6, compiler error

    I was tying to build my project where I use RSBarcodes but I get a compiler error saying that: Value of type 'AVMetadataMachineReadableCodeObject' has no member 'corners'

    It occurs on RSCodeReaderViewController.swift at line 401.

    How can I fix it?

    opened by AndrexOfficial 5
  • RSBarcodes.framework

    RSBarcodes.framework

    Hi guys, sorry to bother you about this but I wasn't able to run the project, it seems there are the RSBarcodes.framework file missing. Can you help me, please?

    opened by marquiano 5
  • How can I generate interleaved2of5 barcode?

    How can I generate interleaved2of5 barcode?

    I can't generate interleaved2of5 barcode image. This is my code, it's the same as the example, I just changed the machineReadableCodeObjectType and it's returning nil.

            let gen = RSUnifiedCodeGenerator.shared
            gen.fillColor = UIColor.white
            gen.strokeColor = UIColor.black
            print ("generating image with barcode: " + barcode)
            if let image = gen.generateCode(barcode, machineReadableCodeObjectType: AVMetadataObject.ObjectType.interleaved2of5.rawValue) {
                self.barcodeImageView.layer.borderWidth = 1
                self.barcodeImageView.image = RSAbstractCodeGenerator.resizeImage(image, targetSize: self.barcodeImageView.bounds.size, contentMode: UIViewContentMode.bottomRight)
            }
    
    opened by damboscolo 4
  • Not showing anything

    Not showing anything

    I have set up a ViewController as described, it worked a few times and I was able to scan codes, however now it just shows a black screen. I've given it access to my camera so I am not sure how to fix this issue. Any ideas?

    opened by dtfiedler 4
  • Active Scanning Area

    Active Scanning Area

    I can't seem to figure out why the barcodes are only scanned when it's in the top half of the camera feed. This is true in portrait and landscape orientation. Is this expected behavior?

    opened by Gerst20051 4
  • Not handling rotation

    Not handling rotation

    The scanner view (actually the AVCaptureVideoPreviewLayer) does not handle rotation properly. I could make it better by adding this in RSCodeReaderViewController.swift - however the orientation is still wrong when the initial device orientation is not portrait (such as with an iPad).

    override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
        let previousTransform = layer!.affineTransform()
        let rotation = coordinator.targetTransform()
        let newTransform = CGAffineTransformConcat(previousTransform, CGAffineTransformInvert(rotation))
        layer!.setAffineTransform(newTransform)
        layer!.frame.origin = CGPointZero
    }
    

    P.S: Thanks for this great library!

    opened by arytbk 4
  • Is it possible to use this library omitting features accessing iPhone camera because I do not use camera feature in my app and would like to remove NSCameraUsageDescription in info.plist.

    Is it possible to use this library omitting features accessing iPhone camera because I do not use camera feature in my app and would like to remove NSCameraUsageDescription in info.plist.

    Hello.

    Is it possible to use this library omitting features accessing iPhone camera because I do not use camera feature in my app (only displaying barcode on UIImageView) and would like to remove NSCameraUsageDescription in info.plist. In fact my app got a following mail from Apple and failed to submit:

    ITMS-90683: Missing Purpose String in Info.plist
     
    Your app’s code references one or more APIs that access sensitive user data.
    The app’s Info.plist file should contain a NSCameraUsageDescription key with a user-facing purpose string explaining clearly and completely why your app needs the data.
    

    Thank you.

    opened by Satoru-PriChan 3
  • Invalid CFBundleIdentifier

    Invalid CFBundleIdentifier

    Hi! Using RSBarcodes_Swift via SPM in a project results in an error message when trying to upload to TestFlight:

    ERROR ITMS-90049: This bundle is invalid. The bundle at path <...> has an invalid CFBundleIdentifier 'RSBarcodes_Swift' There are invalid characters(characters that are not dots, hyphen and alphanumerics) that have been replaced with their code point 'RSBarcodes\u005fSwift'

    opened by szilagyilev 0
  • 'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead on iOS 15 Betas.

    'shared' is unavailable in application extensions for iOS: Use view controller based solutions where appropriate instead on iOS 15 Betas.

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

    This is a new error popping up on the iOS 15 for SwiftUI Applications. It seems to be tied to: let statusBarOrientation = UIApplication.shared.statusBarOrientation

    opened by xxTigerShark 5
  • Support for BUILD_LIBRARIES_FOR_DISTRIBUTION=YES

    Support for BUILD_LIBRARIES_FOR_DISTRIBUTION=YES

    Hello,

    Swift 5.1 introduced Module stability. I was wondering, what do we nee do to do add Support for BUILD_LIBRARIES_FOR_DISTRBUTION set to YES. This is so the module can be stable and won't need to be recompiled for every Xcode release.

    Thanks

    opened by acicartagena 0
  • How to change color of resized barcode?

    How to change color of resized barcode?

    Hi, Here is a code I use to generate barcode:

    RSUnifiedCodeGenerator.shared.strokeColor = .red RSUnifiedCodeGenerator.shared.fillColor = .blue result = RSUnifiedCodeGenerator.shared.generateCode("2166529V", machineReadableCodeObjectType: AVMetadataObject.ObjectType.aztec.rawValue) result = RSAbstractCodeGenerator.resizeImage(result, scale: 10)

    The problem that after resizing the barcode doesn't keep colors I set before. How to set colors after image resizing?

    opened by sotrosh 0
  • Can not generate with Unicode character ¿

    Can not generate with Unicode character ¿

    I am trying to make app which will generate barcode images with special characters like: ¿ ¶ µ but it is not generating correctly

    let unicodeChar: Character = "\u{00B0}" let encodeType = getBarcodeTypeFor(typeStr: card.barcodeType) self.barcodeImageView.image = UIImage().toBarcode(string: ";038388(unicodeChar)", encoder: encodeType, inputCorrectionLevel: .Medium)

    After barcode scan barcode scanner returns text: ;038388%C2%B0 and I want to return it ;038388¿

    opened by nikakirkitadze 0
Releases(5.1.1)
Owner
R0CKSTAR
Cloud Native | Virtualization | macOS/iOS
R0CKSTAR
NextLevel is a Swift camera system designed for easy integration, customized media capture, and image streaming in iOS

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

NextLevel 2k Jan 2, 2023
A light weight & simple & easy camera for iOS by Swift.

DKCamera Description A light weight & simple & easy camera for iOS by Swift. It uses CoreMotion framework to detect device orientation, so the screen-

Bannings 86 Aug 18, 2022
Camera engine for iOS, written in Swift, above AVFoundation. :monkey:

?? The most advanced Camera framework in Swift ?? CameraEngine is an iOS camera engine library that allows easy integration of special capture feature

Remi ROBERT 575 Dec 25, 2022
A Snapchat Inspired iOS Camera Framework written in Swift

Overview SwiftyCam is a a simple, Snapchat-style iOS Camera framework for easy photo and video capture. SwiftyCam allows users to capture both photos

Andrew Walz 2k Dec 21, 2022
KatKit: a Swift UI library for iOS

KatKit KatKit is a Swift UI library for iOS. It looks similar to the Daagn marke

UmaKim 6 Mar 21, 2022
Custom camera with AVFoundation. Beautiful, light and easy to integrate with iOS projects.

?? Warning This repository is DEPRECATED and not maintained anymore. Custom camera with AVFoundation. Beautiful, light and easy to integrate with iOS

Tudo Gostoso Internet 1.4k Dec 16, 2022
📸 iOS Media Capture – features touch-to-record video, slow motion, and photography

PBJVision PBJVision is a camera library for iOS that enables easy integration of special capture features and camera interface customizations in your

patrick piemonte 1.9k Dec 26, 2022
A fully customisable and modern camera implementation for iOS made with AVFoundation.

Features Extremely simple and easy to use Controls autofocus & exposure Customizable interface Code-made UI assets that do not lose resolution quality

Gabriel Alvarado 1.3k Nov 30, 2022
Fasttt and easy camera framework for iOS with customizable filters

FastttCamera is a wrapper around AVFoundation that allows you to build your own powerful custom camera app without all the headaches of using AVFounda

IFTTT 1.8k Dec 10, 2022
An iOS framework that uses the front camera, detects your face and takes a selfie.

TakeASelfie An iOS framework that uses the front camera, detects your face and takes a selfie. This api opens the front camera and draws an green oval

Abdullah Selek 37 Jan 3, 2023
Video and photo camera for iOS

Features: Description Records video ?? takes photos ?? Flash on/off ⚡ Front / Back camera ↕️ Hold to record video ✊ Tap to take photo ?? Tap to focus

André J 192 Dec 17, 2022
Instagram-like photo browser and a camera feature with a few line of code in Swift.

Fusuma is a Swift library that provides an Instagram-like photo browser with a camera feature using only a few lines of code.

Yuta Akizuki 2.4k Dec 31, 2022
A camera designed in Swift for easily integrating CoreML models - as well as image streaming, QR/Barcode detection, and many other features

Would you like to use a fully-functional camera in an iOS application in seconds? Would you like to do CoreML image recognition in just a few more sec

David Okun 868 Dec 29, 2022
Library for iOS Camera API. CameraKit helps you add reliable camera to your app quickly.

CameraKit helps you add reliable camera to your app quickly. Our open source camera platform provides consistent capture results, service that scales, and endless camera possibilities.

CameraKit 628 Dec 27, 2022
iOS camera engine with Vine-like tap to record, animatable filters, slow motion, segments editing

SCRecorder A Vine/Instagram like audio/video recorder and filter framework in Objective-C. In short, here is a short list of the cool things you can d

Simon Corsin 3.1k Dec 25, 2022
A simple, customizable camera control - video recorder for iOS.

LLSimpleCamera: A simple customizable camera - video recorder control LLSimpleCamera is a library for creating a customized camera - video recorder sc

Ömer Faruk Gül 1.2k Dec 12, 2022
Horizon SDK for iOS

Horizon SDK for iOS Horizon SDK is a state of the art real-time video recording / photo shooting iOS library. Some of the features of Horizon SDK incl

Horizon Video Technologies 170 Oct 7, 2022
Privacy-Insight - Read iOS 15 privacy insight .ndjson file into your human brain

Insight Read iOS 15 privacy insight '.ndjson' file into your human brain. Writte

Lakr Aream 151 Nov 11, 2022
Simple Swift class to provide all the configurations you need to create custom camera view in your app

Camera Manager This is a simple Swift class to provide all the configurations you need to create custom camera view in your app. It follows orientatio

Imaginary Cloud 1.3k Dec 29, 2022