iOS User Guide for Barcode Decoding
Requirements
- Supported OS: iOS 11 or higher (iOS 13 and higher recommended).
- Supported ABI: arm64 and x86_64.
- Development Environment: Xcode 13 and above (Xcode 14.1+ recommended).
Add the SDK
There are three ways to add the SDK into your project - Manually, via CocoaPods, or via Swift Package Manager.
Option 1: Add the Frameworks via CocoaPods
-
Add the frameworks in your Podfile, replace
TargetName
with your real target name.target 'HelloWorld' do use_frameworks! pod 'DynamsoftBarcodeReaderBundle','10.2.1101' end
-
Execute the pod command to install the frameworks and generate workspace([TargetName].xcworkspace):
pod install
Option 2: Add the xcframeworks via Swift Package Manager
-
In your Xcode project, go to File –> AddPackages.
-
In the top-right section of the window, search “https://github.com/Dynamsoft/barcode-reader-spm”
-
Select
barcode-reader-spm
then click Add Package -
Check all the xcframeworks and add.
Option 3: Add Local xcframeworks files
-
Download the SDK package from the Dynamsoft Website. After unzipping, you can find the following xcframeworks under the Dynamsoft\Frameworks directory:
-
Drag and drop the xcframeworks into your Xcode project. Make sure to check
Copy items if needed
andCreate groups
to copy the framework into your project’s folder. -
Click on the project settings then go to General –> Frameworks, Libraries, and Embedded Content. Set the Embed field to Embed & Sign for all above xcframeworks.
Build Your First Application
In this section, let’s create a HelloWorld app for reading barcodes from camera video input.
Note:
- XCode 14.2 is used here in this guide.
- You can download the complete Objective-C source code from HelloWorld/DecodeWithCameraEnhancerObjc Sample
- You can download the complete Swift source code from HelloWorld/DecodeWithCameraEnhancer Sample
- DCE is used for camera capture in this guide below. If you use the iOS AVFoundation framework for camera capture, check DecodeWithAVCaptureSession sample on how to add barcode scanning to your app.
Create a New Project
-
Open Xcode and select create a new project.
-
Select iOS > App for your application.
-
Input your product name (DBRHelloworld), interface (StoryBoard) and select the language (Objective-C/Swift).
-
Click on the Next button and select the location to save the project.
-
Click on the Create button to finish.
Include the Frameworks
Add the SDK to your new project. There are several ways to do this, all of which are explained in this section for more details.
Initialize the License
Dynamsoft Barcode Reader needs a valid license to work.
-
Implement the protocol
LicenseVerificationListener
through class ViewController:- Objective-C
- Swift
-
#import <DynamsoftLicense/DynamsoftLicense.h> @interface ViewController () <DSLicenseVerificationListener>
-
import DynamsoftLicense class ViewController: UIViewController, LicenseVerificationListener
-
Add the following code to initialize the license in method
application:didFinishLaunchingWithOptions:
and receive the callback message :- Objective-C
- Swift
-
- (void)setLicense { [DSLicenseManager initLicense:@"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" verificationDelegate:self]; } - (void)onLicenseVerified:(BOOL)isSuccess error:(nullable NSError *)error { if (!isSuccess && error != nil) { NSLog(@"error: %@", error); } }
-
func setLicense() { LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9", verificationDelegate: self) } func onLicenseVerified(_ isSuccess: Bool, error: Error?) { if !isSuccess { if let error = error { print("\(error.localizedDescription)") } } }
Note:
- Network connection is required for the license to work.
- The license string here will grant you a time-limited trial license.
- You can request a 30-day trial license via the Request a Trial License link.
- If you download the Installation Package, it comes with a 30-day trial license by default.
Configure the Camera Enhancer
-
Import all the headers that you will need in the
ViewController
file.- Objective-C
- Swift
-
#import <DynamsoftCameraEnhancer/DynamsoftCameraEnhancer.h> #import <DynamsoftCore/DynamsoftCore.h> #import <DynamsoftBarcodeReader/DynamsoftBarcodeReader.h> #import <DynamsoftCaptureVisionRouter/DynamsoftCaptureVisionRouter.h>
-
import DynamsoftCameraEnhancer import DynamsoftCaptureVisionRouter import DynamsoftBarcodeReader import DynamsoftCore
-
Initialize
CameraEnhancer
andCameraView
and add configurations for theCameraEnhancer
.- Objective-C
- Swift
-
@interface ViewController () <DSLicenseVerificationListener> @property (nonatomic, strong) DSCameraView *cameraView; @property (nonatomic, strong) DSCameraEnhancer *dce; @end ... @implementation ViewController - (void)setUpCamera { self.cameraView = [[DSCameraView alloc] initWithFrame:self.view.bounds]; self.cameraView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; [self.view insertSubview:self.cameraView atIndex:0]; self.dce = [[DSCameraEnhancer alloc] init]; self.dce.cameraView = self.cameraView; } ...
-
var cameraView:CameraView! let dce = CameraEnhancer() ... func setUpCamera() { cameraView = .init(frame: view.bounds) cameraView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.insertSubview(cameraView, at: 0) dce.cameraView = cameraView }
Configure the Barcode Decoding Task via CaptureVisionRouter
-
Initialize the
CaptureVisionRouter
and bind with theCameraEnhancer
instance.- Objective-C
- Swift
-
@interface ViewController () <DSLicenseVerificationListener> @property (nonatomic, strong) DSCaptureVisionRouter *cvr; @end ... @implementation ViewController - (void)setUpDCV { self.cvr = [[DSCaptureVisionRouter alloc] init]; NSError *error; [self.cvr setInput:self.dce error:&error]; if (error != nil) { NSLog(@"error: %@", error); } }
-
let cvr = CaptureVisionRouter() ... func setUpDCV() { try! cvr.setInput(dce) }
-
Implement
onDecodedBarcodesReceived
to receive the barcode decoding results and add this result receiver to the current CVR object.- Objective-C
- Swift
-
/**Add CapturedResultReceiver to your ViewController.*/ @interface ViewController () <DSLicenseVerificationListener, DSCapturedResultReceiver> ... - (void)setUpDCV { ... [self.cvr addResultReceiver:self]; } /**Implement onDecodedBarcodesReceived method of CaptureResultReceiver to receive the barcode decoding results.*/ - (void)onDecodedBarcodesReceived:(DSDecodedBarcodesResult *)result { if (result.items.count > 0) { dispatch_async(dispatch_get_main_queue(), ^{ [self.cvr stopCapturing]; }); NSString *message; for (DSBarcodeResultItem *item in result.items) { message = [NSString stringWithFormat:@"\nFormat: %@\nText: %@\n", item.formatString, item.text]; } [self showResult:@"Results" message:message completion:^{ [self.cvr startCapturing:DSPresetTemplateReadBarcodes completionHandler:nil]; }]; } } - (void)showResult:(NSString *)title message:(NSString *)message completion:(void (^)(void))completion { dispatch_async(dispatch_get_main_queue(), ^{ UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completion(); }]]; [self presentViewController:alert animated:YES completion:nil]; }); }
-
/**Add CapturedResultReceiver to your ViewController.*/ class ViewController: UIViewController, CapturedResultReceiver, LicenseVerificationListener { ... func setUpDCV() { ... /**Add your CaptureResultReceiver to the CaptureVisionRouter.*/ cvr.addResultReceiver(self) } /**Implement onDecodedBarcodesReceived method of CaptureResultReceiver to receive the barcode decoding results.*/ func onDecodedBarcodesReceived(_ result: DecodedBarcodesResult) { if let items = result.items, items.count > 0 { DispatchQueue.main.async { self.cvr.stopCapturing() } var message = "" for item in items { message = String(format:"\nFormat: %@\nText: %@\n", item.formatString, item.text) } showResult("Results", message) { self.cvr.startCapturing(PresetTemplate.readBarcodes.rawValue) } } } private func showResult(_ title: String, _ message: String, completion: @escaping () -> Void) { DispatchQueue.main.async { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completion() })) self.present(alert, animated: true, completion: nil) } } }
Configure viewDidLoad, viewWillAppear, viewWillDisappear
Now that all of the main functions are defined and configured, let’s finish things off on the code side of things by completing the viewDidLoad
, viewWillAppear
, and viewWillDisappear
functions.
- Objective-C
- Swift
- (void)viewDidLoad { [super viewDidLoad]; /**Do any additional setup after loading the view.*/ [self setLicense]; [self setUpCamera]; [self setUpDCV]; } - (void)viewWillAppear:(BOOL)animated { [self.dce open]; [self.cvr startCapturing:DSPresetTemplateReadBarcodes completionHandler:^(BOOL isSuccess, NSError * _Nullable error) { if (!isSuccess && error != nil) { [self showResult:@"Error" message:error.localizedDescription completion:nil]; } }]; [super viewWillAppear:animated]; } - (void)viewWillDisappear:(BOOL)animated { [self.dce close]; [self.cvr stopCapturing]; [super viewWillDisappear:animated]; } ...
override func viewDidLoad() { super.viewDidLoad() /**Do any additional setup after loading the view.*/ setLicense() setUpCamera() setUpDCV() } override func viewWillAppear(_ animated: Bool) { dce.open() // Start capturing when the view will appear. If success, you will receive results in the CapturedResultReceiver. Otherwise you will receive the error message in a dialog. cvr.startCapturing(PresetTemplate.readBarcodes.rawValue) { isSuccess, error in if (!isSuccess) { if let error = error { self.showResult("Error", error.localizedDescription) } } } super.viewWillAppear(animated) } override func viewWillDisappear(_ animated: Bool) { dce.close() cvr.stopCapturing() super.viewWillDisappear(animated) } ...
Configure Camera Permissions
Add Privacy - Camera Usage Description to the info.plist
of your project to request camera permission. An easy way to do this is to access your project settings, go to Info and then add this Privacy property to the iOS target properties list.
Additional Steps for iOS 12 or Lower Versions
If your iOS version is less than 13, please add the following additional steps:
- Remove the methods
application:didDiscardSceneSessions:
andapplication:configurationForConnectingSceneSession:options:
from yourAppDelegate
file. - Remove the
SceneDelegate.Swift
file (SceneDelegate.h
&SceneDelegate.m
for Objective-C). - Remove the
Application Scene Manifest
from your info.plist file. -
Declare the window in your
AppDelegate.Swift
file (AppDelegate.h
for Objective-C).- Objective-C
- Swift
-
@interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
-
import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? }
Run the Project
- Select the device that you want to run your app on. Please note that you will require a physical device to run the application on. If you run the app on a simulator, you will experience some errors at runtime as a physical camera component is required. If you have an M1 Macbook (or a later model) you can run the app on your Macbook directly as it has the same architecture as your iPhone/iPad.
- Run the project, then your app will be installed on your device.
You can download the complete source code here:
Next Steps
From this page, you have learned how to create a simple video barcode decoding app. In the next steps, the following pages will help you on adding configurations to enhance your barcode reader.
Explore Features
If you want to explore the many features of the SDK and learn how to use them to best process the images you read in your application, read the articles in Explore Features.
Check Use Cases
If you want to check how the SDK works in popular use cases, read the articles in Use Cases.
Using AVFoundation with DBR
If you use the iOS AVFoundation framework to activate the camera (instead of the Dynamsoft Camera Enhancer), DecodeWithAVCaptureSession sample will guide you on how to add barcode scanning to your app.