Skip to content

Instantly share code, notes, and snippets.

@aoriani
Created February 29, 2016 02:43
Show Gist options
  • Save aoriani/19ccaf7f3fa68bcd68aa to your computer and use it in GitHub Desktop.
Save aoriani/19ccaf7f3fa68bcd68aa to your computer and use it in GitHub Desktop.
A simple barcode implementation code snippet for iOS 9
//
// ViewController.swift
// BarcodeReader
//
// Created by Andre Oriani on 2/28/16.
// Copyright © 2016 Orion. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
private var captureSession: AVCaptureSession?
private var previewLayer: AVCaptureVideoPreviewLayer?
private var detectionFrame: UIView!
@IBOutlet weak var messagr: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
try captureDevice.lockForConfiguration()
captureDevice.focusMode = .ContinuousAutoFocus
captureDevice.exposureMode = .ContinuousAutoExposure
captureDevice.unlockForConfiguration()
let input = try AVCaptureDeviceInput(device: captureDevice)
captureSession = AVCaptureSession()
captureSession?.addInput(input)
let captureMetadata = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadata)
captureMetadata.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
captureMetadata.metadataObjectTypes = [AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeQRCode]
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer?.frame = view.layer.bounds
view.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
view.bringSubviewToFront(messagr)
detectionFrame = UIView()
detectionFrame.layer.borderColor = UIColor.greenColor().CGColor
detectionFrame.layer.borderWidth = 2
view.addSubview(detectionFrame)
view.bringSubviewToFront(detectionFrame)
} catch {
print ("error")
}
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
if metadataObjects == nil || metadataObjects.count == 0 {
detectionFrame.frame = CGRectZero
messagr.text = "No barcodes"
return
}
let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
let barcodeObject = previewLayer?.transformedMetadataObjectForMetadataObject(metadataObject)
detectionFrame.frame = (barcodeObject?.bounds)!
messagr.text = metadataObject.stringValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment