Dev Center
Swift
Objective-C
Table of contents

Thanks for downloading Dynamsoft Barcode Reader Package!

Your download will start shortly. If your download does not begin, click here to retry.

Getting Started with iOS

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.

Add the Frameworks Manually

  1. Download the SDK package from the Dynamsoft Website. After unzipping, you can find the following xcframeworks under the Dynamsoft\Frameworks directory:
File Description
DynamsoftCaptureVisionRouter.xcframework The Capture Vision Router library is used to interact with image-processing and semantic-processing products in the applications. It accepts an image source and returns processing results which may contain final results or intermediate results.
DynamsoftBarcodeReader.xcframework The Dynamsoft Barcode Reader library, which includes 1D and 2D barcodes recognition algorithm and related APIs.
DynamsoftCore.xcframework The core library, which includes common basic structures and intermediate result related APIs.
DynamsoftImageProcessing.xcframework The image processing library, which incorporates a collection of basic and specialized image processing algorithms.
DynamsoftLicense.xcframework The license library, which includes license related APIs.
DynamsoftCameraEnhancer.xcframework (Optional) The Dynamsoft Camera Enhancer (DCE) SDK provides camera control, camera enhancements, and basic UI configuration features.
DynamsoftUtility.xcframework (Optional) The utility library, which includes multiple implementations of image source adapters, result filter, image exporter, and other utility APIs etc.
  1. Drag and drop the xcframeworks into your Xcode project. Make sure to check Copy items if needed and Create groups to copy the framework into your project’s folder.

  2. 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.

Add the Frameworks via CocoaPods

  1. Add the frameworks in your Podfile, replace TargetName with your real target name.

    target 'HelloWorld' do
       use_frameworks!
    
    pod 'DynamsoftCaptureVisionRouter','2.0.21'
    pod 'DynamsoftBarcodeReader','10.0.21'
    pod 'DynamsoftCameraEnhancer','4.0.2'
    pod 'DynamsoftCore','3.0.20'
    pod 'DynamsoftLicense','3.0.30'
    pod 'DynamsoftImageProcessing','2.0.21'
    pod 'DynamsoftUtility','1.0.21'
    
    end
    
  2. Execute the pod command to install the frameworks and generate workspace([TargetName].xcworkspace):

    pod install
    

Add the xcframeworks via Swift Package Manager

  1. In your Xcode project, go to File –> AddPackages.

  2. In the top-right section of the window, search “https://github.com/Dynamsoft/barcode-reader-spm”

  3. Select barcode-reader-spm then click Add Package

  4. Check all the xcframeworks and add.

Build Your First Application

In this section, let’s create a HelloWorld app for reading barcodes from camera video input.

Note:

Create a New Project

  1. Open Xcode and select create a new project.

  2. Select iOS > App for your application.

  3. Input your product name (DBRHelloworld), interface (StoryBoard) and select the language (Objective-C/Swift).

  4. Click on the Next button and select the location to save the project.

  5. 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. It is recommended to put the license activation code in the AppDelegate file. You must first obtain a trial license if you don’t have one. In order to request a trial license, please request one via the customer portal. Now that you have your trial license, let’s implement it in code.

  1. Implement the protocol LicenseVerificationListener through class AppDelegate:

    • Objective-C
    • Swift
    1. #import <DynamsoftLicense/DynamsoftLicense.h>
      @interface AppDelegate ()<DSLicenseVerificationListener>
      
    2. import DynamsoftLicense
      @main
      class AppDelegate: LicenseVerificationListener
      
  2. Add the following code to initialize the license in method application:didFinishLaunchingWithOptions: and receive the callback message :

    • Objective-C
    • Swift
    1. @implementation AppDelegate
      - (void)onLicenseVerified:(BOOL)isSuccess error:(nullable NSError *)error {
         if (!isSuccess && error != nil) {
            NSLog(@"%@", error);
         }
      }
      - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions {
         /**Override point for customization after application launch.*/
         [DSLicenseManager initLicense:@"DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" verificationDelegate:self];
         return YES;
      }
      
    2. class AppDelegate: UIResponder, UIApplicationDelegate, LicenseVerificationListener {
         func onLicenseVerified(_ isSuccess: Bool, error: Error?) {
            if !isSuccess {
               if let error = error {
                  print("\(error.localizedDescription)")
               }
            }
         }
         func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            /**Override point for customization after application launch.*/
            LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9", verificationDelegate: self)
            return true
         }
      }
      

    Note:

    • Network connection is required for the license to work.
    • The license string here will grant you a time-limited trial license.
    • If the license has expired, you can go to the Customer Portal to request for an extension.
    • If you download the Installation Package, it comes with a 30-day trial license.

Configure the Camera Enhancer

  1. Import all the headers that you will need in the ViewController file.

    • Objective-C
    • Swift
    1. #import <DynamsoftCameraEnhancer/DynamsoftCameraEnhancer.h>
      #import <DynamsoftCore/DynamsoftCore.h>
      #import <DynamsoftBarcodeReader/DynamsoftBarcodeReader.h>
      #import <DynamsoftCaptureVisionRouter/DynamsoftCaptureVisionRouter.h>
      
    2. import DynamsoftCameraEnhancer
      import DynamsoftCaptureVisionRouter
      import DynamsoftBarcodeReader
      import DynamsoftCore
      
  2. Initialize CameraEnhancer and CameraView and add configurations for the CameraEnhancer.

    • Objective-C
    • Swift
    1. @interface ViewController ()
      @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;
      }
      ...
      
    2. 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

  1. Initialize the CaptureVisionRouter and bind with the CameraEnhancer instance.

    • Objective-C
    • Swift
    1. @interface ViewController ()
      @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);
         }
      }
      
    2. let cvr = CaptureVisionRouter()
      ...
      func setUpDCV() {
         try! cvr.setInput(dce)
      }
      
  2. Implement onDecodedBarcodesReceived to receive the barcode decoding results and add this result receiver to the current CVR object.

    • Objective-C
    • Swift
    1. /**Add CapturedResultReceiver to your ViewController.*/
      @interface ViewController () <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];
         });
      }
      
    2. /**Add CapturedResultReceiver to your ViewController.*/
      class ViewController: UIViewController, CapturedResultReceiver {
         ...
         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
  1. - (void)viewDidLoad {
       [super viewDidLoad];
       /**Do any additional setup after loading the view.*/
       [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];
    }
    ...
    
  2. override func viewDidLoad() {
       super.viewDidLoad()
       /**Do any additional setup after loading the view.*/
       setUpCamera()
       setUpDCV()
    }
    override func viewWillAppear(_ animated: Bool) {
       dce.open()
       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:

  1. Remove the methods application:didDiscardSceneSessions: and application:configurationForConnectingSceneSession:options: from your AppDelegate file.
  2. Remove the SceneDelegate.Swift file (SceneDelegate.h & SceneDelegate.m for Objective-C).
  3. Remove the Application Scene Manifest from your info.plist file.
  4. Declare the window in your AppDelegate.Swift file (AppDelegate.h for Objective-C).

    • Objective-C
    • Swift
    1. @interface AppDelegate : UIResponder <UIApplicationDelegate>
      @property (strong, nonatomic) UIWindow *window;
      @end
      
    2. import UIKit
      @main
      class AppDelegate: UIResponder, UIApplicationDelegate {
         var window: UIWindow?
      }
      

Run the Project

  1. 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.
  2. 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), HelloWorld/DecodeWithAVCaptureSession will guide you on how to add barcode scanning to your app.

Other platforms

This page is compatible for:

Version 7.5.0

Is this page helpful?

YesYes NoNo

In this article:

latest version

  • Latest version
  • Version 9.x
    • Version 9.6.40
    • Version 9.6.20
    • Version 9.6.11
    • Version 9.6.10
    • Version 9.6.0
    • Version 9.4.0
    • Version 9.2.13
    • Version 9.2.11
    • Version 9.2.10
    • Version 9.0.2
    • Version 9.0.1
    • Version 9.0.0
  • Version 8.x
    • Version 8.9.3
    • Version 8.9.1
    • Version 8.9.0
    • Version 8.8.0
    • Version 8.6.0
    • Version 8.4.0
    • Version 8.2.1
    • Version 8.2.0
    • Version 8.1.2
    • Version 8.1.0
    • Version 8.0.0
  • Version 7.x
    • Version 7.6.0
    • Version 7.5.0
Change +