Skip to content

Instantly share code, notes, and snippets.

@humberaquino
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save humberaquino/0448baa12071139cc210 to your computer and use it in GitHub Desktop.
Save humberaquino/0448baa12071139cc210 to your computer and use it in GitHub Desktop.
BarcodeViewController
class BarcodeViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var delegate: BarcodeDelegate?
var captureSession: AVCaptureSession!
var code: String?
override func viewDidLoad() {
super.viewDidLoad()
// You use an AVCaptureSession object to coordinate the flow of data from AV input devices to outputs.
self.captureSession = AVCaptureSession();
// Get the Video device
let videoCaptureDevice: AVCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error: NSError?
// Use to capture data from an AVCaptureDevice object.
let videoInput = AVCaptureDeviceInput.deviceInputWithDevice(videoCaptureDevice, error: &error) as AVCaptureDeviceInput
// Add the input to the session if possible
if self.captureSession.canAddInput(videoInput) {
self.captureSession.addInput(videoInput)
} else {
println("Could not add video input: \(error?.localizedDescription)")
}
// Add the output to the session if possible
let metadataOutput = AVCaptureMetadataOutput()
if self.captureSession.canAddOutput(metadataOutput) {
self.captureSession.addOutput(metadataOutput)
// Add ourselves as delegate to get the output
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]
} else {
println("Could not add metadata output")
}
// Create a preview layer to add it to the ViewController's view
let previewLayer = AVCaptureVideoPreviewLayer(session: self.captureSession)
previewLayer.frame = self.view.layer.bounds
self.view.layer.addSublayer(previewLayer)
// Start the session
self.captureSession.startRunning()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
// This is the delegate'smethod that is called when a code is readed
for metadata in metadataObjects {
let readableObject = metadata as AVMetadataMachineReadableCodeObject
let code = readableObject.stringValue
// If the code is not empty the code is ready and we call out delegate to pass the code.
if !code.isEmpty {
self.captureSession.stopRunning()
self.dismissViewControllerAnimated(true, completion: nil)
self.delegate?.barcodeReaded(code)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment