Skip to content

Instantly share code, notes, and snippets.

@ilares-phunware
Last active January 2, 2023 17:43
Show Gist options
  • Save ilares-phunware/4a2526a8a4d6cbf4ea3eefd160f6a347 to your computer and use it in GitHub Desktop.
Save ilares-phunware/4a2526a8a4d6cbf4ea3eefd160f6a347 to your computer and use it in GitHub Desktop.
import UIKit
import AVFoundation
import Vision
// Note: Please be sure to set the NSCameraUsageDescription key in the project's Info.plist file.
class VisionScannerViewController: UIViewController {
private let captureSession = AVCaptureSession()
private var barcodeRequest: VNDetectBarcodesRequest?
override func viewDidLoad() {
super.viewDidLoad()
setupBarcodeRequest()
setupCaptureSession()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSession.startRunning()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
captureSession.stopRunning()
}
}
// MARK: - AVCaptureVideoDataOutputSampleBufferDelegate
extension VisionScannerViewController: AVCaptureVideoDataOutputSampleBufferDelegate {
func captureOutput(_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection) {
guard let barcodeRequest = barcodeRequest,
let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
return
}
let imageRequestHandler = VNImageRequestHandler(
cvPixelBuffer: pixelBuffer,
orientation: .right)
do {
try imageRequestHandler.perform([barcodeRequest])
} catch {
// TODO: Handle Error
print(error)
}
}
}
// MARK: - Private Methods
private extension VisionScannerViewController {
func processBarcodeRequestResults(request: VNRequest, error: Error?) {
if let error = error {
// TODO: Error Handling
print(error)
return
}
guard let barcodeObservations = request.results as? [VNBarcodeObservation] else { return }
for barcodeObservation in barcodeObservations {
print("payload : \(barcodeObservation.payloadStringValue ?? "")")
print("confidence : \(barcodeObservation.confidence)")
print("symbology : \(barcodeObservation.symbology)", terminator: "\n\n")
}
}
func setupBarcodeRequest() {
barcodeRequest = VNDetectBarcodesRequest(completionHandler: processBarcodeRequestResults)
barcodeRequest?.symbologies = [.code128, .qr]
}
func setupCaptureSession() {
captureSession.sessionPreset = .hd1280x720
let videoCaptureDevice = AVCaptureDevice
.default(.builtInWideAngleCamera, for: .video, position: .back)
guard let device = videoCaptureDevice,
let captureDeviceInput = try? AVCaptureDeviceInput(device: device),
captureSession.canAddInput(captureDeviceInput) else {
return
}
captureSession.addInput(captureDeviceInput)
let captureOutput = AVCaptureVideoDataOutput()
captureOutput.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
captureOutput.setSampleBufferDelegate(self, queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))
captureSession.addOutput(captureOutput)
let capturePreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
capturePreviewLayer.videoGravity = .resizeAspectFill
capturePreviewLayer.connection?.videoOrientation = .portrait
capturePreviewLayer.frame = view.frame
view.layer.insertSublayer(capturePreviewLayer, at: 0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment