AVCaptureVideo not showing label

313 views Asked by At

I am trying to retain the objects from the console to be shown in as a label(classifierText). The warning of "UILabel.text must be used from main thread only" appears. What seems to the problem as to why the items are being shown as the label?

var previewLayer: AVCaptureVideoPreviewLayer!

let classifierText: UILabel = {
    let classifier = UILabel()
    classifier.translatesAutoresizingMaskIntoConstraints = false
    classifier.textColor = .black
    classifier.font = UIFont(name: "Times-New-Roman", size: 10)
    classifier.textAlignment = .center
    return classifier
}()

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
    guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
    guard let model =  try? VNCoreMLModel(for: Resnet50().model) else { return }
    let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
    let results = finishedReq.results as?  [VNClassificationObservation]
    let firstObservation = results!.first
    self.classifierText.text = "\(firstObservation!.identifier as String)"
1

There are 1 answers

0
Matthijs Hollemans On

The method captureOutput(sampleBuffer, etc) does not run on the main thread. So you're trying to change the label from a thread that is not the main thread.

The solution is to schedule the work on the main thread, like so:

DispatchQueue.main.async {
    self.classifierText.text = "\(firstObservation!.identifier as String)"
}