iOS General Example

Creating Barkoder Configuration #

The createBarkoderConfig method is responsible for setting up the configuration required to initiate barcode scanning. This configuration includes the license key necessary for validating and activating the SDK. 

If the license key is invalid or missing, the scan results will contain an "UNLICENSED" prefix and random asterisks.

                   private func createBarkoderConfig() {
        // In order to perform scanning, config property need to be set before
        // If license key is not valid you will receive results with asterisks inside
        barkoderView.config = BarkoderConfig(licenseKey: "LICENSE_KEY") { licenseResult in
            print("Licensing SDK: \(licenseResult)")
        }
    }
            

Enabling Symbologies #

Here’s a detailed and refined explanation of how you can enable individual symbologies for barcode scanning using both direct configuration and JSON configuration in Swift

Enabling Symbologies Directly #

You can enable individual symbologies directly by setting the enabled property of each symbology in the decoderConfig object. Here’s a method that demonstrates how to do this:

                private func setActiveBarcodeTypes() {
    guard let decoderConfig = barkoderView.config?.decoderConfig else { return }
    decoderConfig.ean13.enabled = true
    decoderConfig.upcA.enabled = true
    decoderConfig.qr.enabled = true
 }
            

Enabling Symbologies via JSON Configuration #

Alternatively, you can enable symbologies using a JSON configuration. This approach allows you to define the symbology settings in a more structured and flexible manner. Here’s how you can do it:

                private func setActiveBarcodeTypes() {
    guard let config = barkoderView.config else { return }
    let json: [String: Any] = [
      “decoder”: [
        “QR”: [
          “enabled”: true
        ],
        “Aztec”: [
          “enabled”: true
        ],
        “Aztec Compact”: [
          “enabled”: true
        ],
        “QR Micro”: [
          “enabled”: true
        ]
      ]
    ]
    do {
      let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
      BarkoderHelper.applyConfigSettingsFromJson(config, jsonData: jsonData) { updatedConfig, error in
        if let error {
          print(“\(error.localizedDescription)“)
        }
      }
    } catch {
      print(“Error converting dictionary to JSON data: \(error)“)
    }
  }
Starting scan
  func startScanning() {
    do {
      try barkoderView.startScanning(self)
    } catch {
      print(error.localizedDescription)
    }
  }

            

Setting barkoder settings #

The setBarkoderSettings method 

Next define a function setBarkoderSettings where we will update our settings for the barcode scanner view (bkdView).

In our case we will enable image results and include barcode location within the image, also make the region of interest visible and enable pinch-to-zoom functionality.

Finally, configure the ROI to cover the central 90% of the scanner view.

These configurations enhance the user experience by providing more detailed scan results, interactive zooming, and visual feedback about the scan area.

                    private func setBarkoderSettings() {
        guard let config = barkoderView.config else { return }
            
        // These are optional settings, otherwise default values will be used
        config.imageResultEnabled = true
        config.locationInImageResultEnabled = true
        config.regionOfInterestVisible = true
        config.pinchToZoomEnabled = true
        try? config.setRegionOfInterest(CGRect(x: 5, y: 5, width: 90, height: 90))
    }
            

Starting Scan #

The startScanning method initiates the scanning process. If there is an error during the start process, the error message is printed for debugging. 

                func startScanning() {
    if !scanningInProcess {
        try? barkoderView.startScanning(self)
    } else {
        barkoderView.stopScanning()
    }
    
    resetResult()
    scanningInProcess.toggle()
 }
            

Handling Results #

Implementing the BarkoderResultDelegate allows your view controller to receive scanning results. The scanningFinished method is called when scanning is complete, providing the results, optional thumbnails, and the captured image.

                func scanningFinished(_ decoderResults: [DecoderResult], thumbnails: [UIImage]?, image: UIImage?) {
    if let decoderResult = decoderResults.first, let thumbnail = thumbnails.first {
        showResult(decoderResult, thumbnail: thumbnail, image: image)
    }
       
    scanningInProcess = false
}

            

showResult #

The showResult function updates the UI based on the state of the scanning process and the results obtained

                private func showResult(_ decoderResult: DecoderResult, thumbnail: UIImage?, image: UIImage?) {
    resultImageView.image = image
    thumbnailImageView.image = thumbnail

    typeResultLabel.text = decoderResult.barcodeTypeName
        
    resultValueLabel.text = decoderResult.textualData
    resultFromScanning = decoderResult.textualData
        
    let extras: [String] = decoderResult.extra.map {
        return "\($0): \($1)"
    }
        
    extrasResultLabel.text = extras.joined(separator: "\n")
}
            

Complete solution #

In the end, let's merge all of these functions and implement them within our main view controller.

This code would go in your view controller, and of course it will be different for your project, but generally it's a good starting point to have.

                import UIKit
import BarkoderSDK

final class ViewController: UIViewController {

    // MARK: - IBOutlets
    
    @IBOutlet private weak var barkoderView: BarkoderView!
    @IBOutlet private weak var resultImageView: UIImageView!
    @IBOutlet private weak var thumbnailImageView: UIImageView!
    @IBOutlet private weak var introLabel: UILabel!
    @IBOutlet private weak var typeHolderView: UIView!
    @IBOutlet private weak var resultHolderView: UIView!
    @IBOutlet private weak var extrasHolderView: UIView!
    @IBOutlet private weak var scanButton: ScanButton!
    
    @IBOutlet private weak var typeResultLabel: UILabel!
    @IBOutlet private weak var resultValueLabel: UILabel!
    @IBOutlet private weak var extrasResultLabel: UILabel!
    
    // MARK: - Constants
    
    private let holderViewBackgroundColor: UIColor = .white
    private let barkoderBackgroundColor: UIColor = UIColor(red: 230/255.0, green: 230/255.0, blue: 230/255.0, alpha: 1)
    private let resultsMaximumLines = 2
    private let holderViewCornerRadius = 16.0
    
    private var resultFromScanning: String?
    
    // MARK: - Life cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        createBarkoderConfig()
        setActiveBarcodeTypes()
        setBarkoderSettings()
    }

    // MARK: - Private methods
    
    private func setupUI() {
        title = "Barkoder Sample (v\(iBarkoder.GetVersion()))"

        view.backgroundColor = UIColor(red: 0.96, green: 0.96, blue: 0.96, alpha: 1.00)
        
        barkoderView.backgroundColor = barkoderBackgroundColor
        
        typeHolderView.backgroundColor = holderViewBackgroundColor
        typeHolderView.layer.cornerRadius = holderViewCornerRadius
        
        resultHolderView.backgroundColor = holderViewBackgroundColor
        resultHolderView.layer.cornerRadius = holderViewCornerRadius
        resultHolderView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(didTapViewAllResult)))
        
        extrasHolderView.backgroundColor = holderViewBackgroundColor
        extrasHolderView.layer.cornerRadius = holderViewCornerRadius
        
        var configuration = UIButton.Configuration.filled()
        configuration.image = UIImage(named: "btn_ffa")
        configuration.baseBackgroundColor = UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1.00)
        configuration.cornerStyle = .capsule
        scanButton.configuration = configuration
        scanButton.layer.shadowColor = UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1.00).cgColor
        scanButton.layer.shadowOpacity = 0.05
        scanButton.layer.shadowOffset = .zero
        scanButton.layer.shadowRadius = 10

        typeResultLabel.numberOfLines = resultsMaximumLines
        resultValueLabel.numberOfLines = resultsMaximumLines
        extrasResultLabel.numberOfLines = resultsMaximumLines
    }
    
    private func createBarkoderConfig() {
        // In order to perform scanning, config property need to be set before
        // If license key is not valid you will receive results with asterisks inside
        barkoderView.config = BarkoderConfig(licenseKey: "LICENSE_KEY") { licenseResult in
            print("Licensing SDK: \(licenseResult)")
        }
    }
    
    private func setActiveBarcodeTypes() {
        guard let decoderConfig = barkoderView.config?.decoderConfig else { return }
        decoderConfig.ean13.enabled = true
        decoderConfig.upcA.enabled = true
        decoderConfig.qr.enabled = true
    }
    
    private func setBarkoderSettings() {
        guard let config = barkoderView.config else { return }
            
        // These are optional settings, otherwise default values will be used
        config.imageResultEnabled = true
        config.locationInImageResultEnabled = true
        config.regionOfInterestVisible = true
        config.closeSessionOnResultEnabled = true

        try? config.setRegionOfInterest(CGRect(x: 5, y: 5, width: 90, height: 90))
    }
    
    private func showResult(_ decoderResult: DecoderResult, thumbnail: UIImage?, image: UIImage?) {
        resultImageView.image = image
        thumbnailImageView.image = thumbnail

        typeResultLabel.text = decoderResult.barcodeTypeName
        
        resultValueLabel.text = decoderResult.textualData
        resultFromScanning = decoderResult.textualData
        
        let extras: [String] = decoderResult.extra.map {
            return "\($0): \($1)"
        }
        
        extrasResultLabel.text = extras.description
    }
    
    // MARK: - IBActions
    
    @IBAction private func didTapScanButton(_ sender: Any) {
        introLabel.isHidden = true
        startScanning()
    }
    
    @objc private func didTapViewAllResult() {
        guard (resultFromScanning != nil) else { return }
        
        let alert = UIAlertController(title: "Full result", message: resultFromScanning, preferredStyle: .alert)
        let continueAction = UIAlertAction(title: "Continue", style: .default)
        alert.addAction(continueAction)
        DispatchQueue.main.async {
            self.present(alert, animated: true)
        }
    }
    
}

class ScanButton: UIButton {
    var isScanning: Bool {
        set {
            self.isSelected = newValue
        }
        get {
            return self.isSelected
        }
    }
}

extension ViewController: BarkoderResultDelegate {

    func scanningFinished(_ decoderResults: [DecoderResult], thumbnails: [UIImage]?, image: UIImage?) {
        if let decoderResult = decoderResults.first, let thumbnail = decoderResults.first {
            showResult(decoderResult, thumbnail: thumbnail, image: image)
        }
        
        scanButton.isScanning = false
    }

    func startScanning() {
        let isScanning = scanButton.isScanning
        if !isScanning {
            resultImageView.image = nil
            try? barkoderView.startScanning(self)
        } else {
            barkoderView.stopScanning()
        }
        
        scanButton.isScanning.toggle()
    }

}

            

To try this example you can get our SDK directly from our github repository

However, as mentioned, the SDK will work without a license but the results will be filled with Asterisks (*). To get full results one would need a license key, which can be obtained from our website.  

Page Contents

History:

close