How do I scan barcodes with AVFoundation in Swift?

To scan barcodes using AVFoundation in Swift, you'll need to set up an AVCaptureSession, configure the capture device, and implement the delegate methods to handle the barcode scanning results. Below is an example of how to implement barcode scanning in your iOS application.

import AVFoundation import UIKit class BarcodeScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { var captureSession: AVCaptureSession! var previewLayer: AVCaptureVideoPreviewLayer! override func viewDidLoad() { super.viewDidLoad() captureSession = AVCaptureSession() guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return } let videoInput: AVCaptureDeviceInput do { videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice) } catch { return } if (captureSession.canAddInput(videoInput)) { captureSession.addInput(videoInput) } else { return } let metadataOutput = AVCaptureMetadataOutput() if (captureSession.canAddOutput(metadataOutput)) { captureSession.addOutput(metadataOutput) metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) metadataOutput.metadataObjectTypes = [.ean8, .ean13, .pdf417, .qr] // Specify barcode types } else { return } previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer.frame = view.layer.bounds previewLayer.videoGravity = .resizeAspectFill view.layer.addSublayer(previewLayer) captureSession.startRunning() } func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) { if let metadataObject = metadataObjects.first { guard let readableObject = metadataObject as? AVMetadataMachineReadableCodeObject else { return } guard let stringValue = readableObject.stringValue else { return } AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) print("Barcode scanned: \(stringValue)") // Handle barcode value } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if (captureSession.isRunning) { captureSession.stopRunning() } } }

barcode scanning AVFoundation Swift iOS development camera capture