VisionKit 条码扫描器使用 Swift 实现高亮显示

VisionKit Barcode Scanner Enabling Highlights Using Swift

提问人:Summer 提问时间:1/8/2023 更新时间:1/8/2023 访问量:166

问:

我正在学习如何创建条形码扫描仪,并想添加突出显示(当相机识别到数字时,数字周围的黄色方块)

我相信我应该使用 isHighlightingEnabled: true

但我不确定在我的代码中把它放在哪一行。我应该把它放在哪里,我是否需要添加任何东西才能使其工作?

import UIKit
import Vision
import AVFoundation
import SafariServices

@objc class CMWSTVisionReader: UIViewController {
  // MARK: - Private Variables
  var captureSession = AVCaptureSession()
    
    @IBOutlet weak var cameraView: UIView!
    @IBOutlet weak var barcodeResult: UILabel!
    
    // TODO: Make VNDetectBarcodesRequest variable
  lazy var detectBarcodeRequest = VNDetectBarcodesRequest { request, error in
    guard error == nil else {
//      self.showAlert(
//        withTitle: "Barcode error",
//        message: error?.localizedDescription ?? "error")
      return
    }
    self.processClassification(request)
  }

  // MARK: - Override Functions
  override func viewDidLoad() {
    super.viewDidLoad()
    checkPermissions()
    setupCameraLiveView()
  }
  override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // TODO: Stop Session
    captureSession.stopRunning()

  }
}


extension CMWSTVisionReader {
  // MARK: - Camera
  private func checkPermissions() {
    // TODO: Checking permissions
    switch AVCaptureDevice.authorizationStatus(for: .video) {
    // 1
    case .notDetermined:
      AVCaptureDevice.requestAccess(for: .video) { [self] granted in
        if !granted {
          showPermissionsAlert()
        }
      }

    // 2
    case .denied, .restricted:
      showPermissionsAlert()

    // 3
    default:
      return
    }

  }

  private func setupCameraLiveView() {
    // TODO: Setup captureSession
    captureSession.sessionPreset = .hd1280x720

    // TODO: Add input
    // 1
    let videoDevice = AVCaptureDevice
      .default(.builtInWideAngleCamera, for: .video, position: .back)

    // 2
    guard
      let device = videoDevice,
      let videoDeviceInput = try? AVCaptureDeviceInput(device: device),
      captureSession.canAddInput(videoDeviceInput)
      else {
        // 3
        showAlert(
          withTitle: "Cannot Find Camera",
          message: "There seems to be a problem with the camera on your device.")
        return
      }

    // 4
    captureSession.addInput(videoDeviceInput)

    // TODO: Add output
    let captureOutput = AVCaptureVideoDataOutput()
    // TODO: Set video sample rate
    captureOutput.videoSettings =
      [kCVPixelBufferPixelFormatTypeKey as String: Int(kCVPixelFormatType_32BGRA)]
    captureOutput.setSampleBufferDelegate(
      self,
      queue: DispatchQueue.global(qos: DispatchQoS.QoSClass.default))

    captureSession.addOutput(captureOutput)

    configurePreviewLayer()

    // TODO: Run session
    captureSession.startRunning()

  }
    
    

  // MARK: - Vision
  func processClassification(_ request: VNRequest) {
    // TODO: Main logic
    // 1
    guard let barcodes = request.results else { return }
    DispatchQueue.main.async { [self] in
      if captureSession.isRunning {
        view.layer.sublayers?.removeSubrange(1...)

        // 2
        for barcode in barcodes {
          guard
            // TODO: Check for QR Code symbology and confidence score
            let potentialQRCode = barcode as? VNBarcodeObservation,
            potentialQRCode.confidence > 0.9
            else { return }

          // 3
          observationHandler(payload: potentialQRCode.payloadStringValue)

        }
      }
    }

  }

  // MARK: - Handler
  func observationHandler(payload: String?) {
    // TODO: Open it in Safari
    // 1
      
      barcodeResult.text = payload
//      guard
//      let payloadString = payload,
//      let url = URL(string: payloadString),
//      ["http", "https"].contains(url.scheme?.lowercased())
//      else { return }
//
//    // 2
//    let config = SFSafariViewController.Configuration()
//    config.entersReaderIfAvailable = true
//
//    // 3
//    let safariVC = SFSafariViewController(url: url, configuration: config)
//    safariVC.delegate = self
//    present(safariVC, animated: true)

  }
}


// MARK: - AVCaptureDelegation
extension CMWSTVisionReader: AVCaptureVideoDataOutputSampleBufferDelegate {
  func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    // TODO: Live Vision
    // 1
    guard let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
      return
    }

    // 2
    let imageRequestHandler = VNImageRequestHandler(
      cvPixelBuffer: pixelBuffer,
      orientation: .right)

    // 3
    do {
      try imageRequestHandler.perform([detectBarcodeRequest])
    } catch {
      print(error)
    }

  }
}



// MARK: - Helper
extension CMWSTVisionReader {
  private func configurePreviewLayer() {
    let cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer.videoGravity = .resizeAspectFill
    cameraPreviewLayer.connection?.videoOrientation = .portrait
    cameraPreviewLayer.frame = cameraView.frame
    cameraView.layer.insertSublayer(cameraPreviewLayer, at: 0)
  }

  private func showAlert(withTitle title: String, message: String) {
    DispatchQueue.main.async {
      let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
      alertController.addAction(UIAlertAction(title: "OK", style: .default))
      self.present(alertController, animated: true)
    }
  }

  private func showPermissionsAlert() {
    showAlert(
      withTitle: "Camera Permissions",
      message: "Please open Settings and grant permission for this app to use your camera.")
  }
}


// MARK: - SafariViewControllerDelegate
extension CMWSTVisionReader: SFSafariViewControllerDelegate {
  func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    captureSession.startRunning()
  }
}
阵列 Swift 条码扫描 Vision VisionKit

评论

0赞 HangarRash 1/8/2023
isHighlightingEnabled似乎是您似乎没有使用的属性。DataScannerViewController
0赞 Summer 1/9/2023
@HangarRash 谢谢,我该如何使用 DataScannerViewController 以便我可以使用 isHighlightingEnabled ?

答: 暂无答案