-1

I'm trying to take photo and return image data as return type of function. AVFoundation takes picture asynchronous, and my function returns before it's finished, so I get empty bytes.

I tried calling takePicture() with waiting, as said in this reply Waiting until the task finishes but it just freezes UI.

func takePicture() -> Data {

    var imageData: Data?

        self.stillImageOutput?.captureStillImageAsynchronously(from: videoConnection!, completionHandler: { (imageDataBuffer, error) in

            if let result = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: imageDataBuffer!, previewPhotoSampleBuffer: imageDataBuffer!) {
                imageData = result
            }

            // Removing sessions and stop running
        })

    return imageData!
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Possible duplicate of [Wait for async function return value in swift](https://stackoverflow.com/questions/34861337/wait-for-async-function-return-value-in-swift) – Cristik Sep 29 '19 at 19:24

1 Answers1

1

You need a completion

func takePicture(completion:@escaping(Data?) -> ()) {
    self.stillImageOutput?.captureStillImageAsynchronously(from: videoConnection!, completionHandler: { (imageDataBuffer, error) in
        if let result = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: imageDataBuffer!, previewPhotoSampleBuffer: imageDataBuffer!) {
            completion(result)
        }
        else {
              completion(nil)
        }
    })
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87