Using DataScannerViewController with async stream

Hi, The presentation "Capture Machine Readable Codes and Text with VisionKit" mentions at the end that the DataScannerViewController can be used with an async stream. In the presentation, there is a code snipper for the updateViewAsyncStream method, but it's not really used anywhere. How do utilize this when the DataScannerViewController is active and capture the recognized items?

Also there is a sendDidChangeNotification() function sat the end but the compiler complains that it's not in scope.

Thanks.

Accepted Answer

Hi!

  1. Create your data scanner and store it somewhere, like a property of whatever class you're in.
  2. Then present the data scanner and call startScanning().
  3. Call a method similar to the snippet, updateViaAsyncStream(). Yours should grab a stream from the data scanner created in step 1. Iterate it via a for-await-in.

You should then start seeing periodic calls to the code within the loop.

The sendDidChangeNotification() isn't meant to do anything (it's not a method on data scanner). It represents a method you can have in your code. At that point in the sample, currentItems has all the items currently recognized on the screen and you can do whatever you need with it. Hope that helps.

I tried and scanner starts but updateViaAsyncStream() isn't being called: [compiled for iPhone SE]


import VisionKit



class ViewController: UIViewController, DataScannerViewControllerDelegate {

    // omitting other datascanner functions to make code shorter for posting

    

    // Set up Scanner

    let viewController = DataScannerViewController(

        recognizedDataTypes: [ .text(languages: ["en-US"]) ],

        qualityLevel: .balanced,

        recognizesMultipleItems: true,

        isHighFrameRateTrackingEnabled: true,

        isPinchToZoomEnabled: true,

        isGuidanceEnabled: false,

        isHighlightingEnabled: true)



           

    var currentItems: [RecognizedItem] = []



    func updateViaAsyncStream() async {

        print("here")

    }

    

    override func viewDidLoad() {

        super.viewDidLoad()

        viewController.delegate = self

    }

    

    override func viewDidAppear(_ animated: Bool) {

        present(viewController, animated: true) {

            try? self.viewController.startScanning()

            NSLog("scanner started")

        }

    }

}
Using DataScannerViewController with async stream
 
 
Q