admin管理员组

文章数量:1122846

I am having an issue updating the UI from the background thread.

The issue is whenever I set inferenceResult published var to observer the change in UI - I only get one result and then callback from camera frame stops. If I comment setting the published var on result self.inferenceResult = and prints the result - I get the expected result per frame printed in the console continuously. I am trying to print the result continuously in the UI but as soon as I set the published var I only get one result and it stops.

Any ideas, Thanks

class CameraPreviewer: ObservableObject, CameraFeedManagerDelegate {
    @Published var inferenceResult: [ImageClassificationResult] = []
        
    func didOutput(pixelBuffer: CVPixelBuffer) {
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            let results = self.imageClassifier.classify(frame: pixelBuffer) 

            DispatchQueue.main.async {
                self.inferenceResult = resultspactMap { result in
                guard let label = result.label else { return nil }
                return ImageClassificationResult(
                                inferenceTime: result.inferenceTime,
                                label: label,
                                score: result.score
                            )
            }
        }
    }
} 

Here is my View code

struct PreviewView: View {                
     @StateObject private var cameraPreviewer = CameraPreviewer()
    
     var body: some View {        
          VStack {
              Text("Inference Results").font(.headline)
              ScrollView {
                  LazyVStack(alignment: .leading, spacing: 8) {
                      ForEach(cameraPreviewer.inferenceResult) { item in
                          HStack {
                              VStack(alignment: .leading, spacing: 4) { 
                                  Text("Label: \(item.label)")
                                      .font(.body)
                                      .foregroundColor(.primary)

                               }
    //...

本文标签: iosUpdating UI from the background thread image classification Swift UIStack Overflow