如何正确获取图像数据?

How to get image Data properly?

我正在尝试将照片和 return 图像数据作为 return 类型的函数。 AVFoundation 异步拍摄图片,我的函数 returns 在完成之前,所以我得到空字节。

我尝试调用 takePicture() 并等待,如回复中所述 但它只是冻结 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!
}

你需要完成

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)
        }
    })
}