Swift: 如何将从委托接收到的值传递给函数的完成块?

Swift: how to pass a value received from delegate to a function's completion block?

我正在尝试使用 Swift 4.2 中的 AVFoundation 捕捉图像 捕获功能存在于 CameraEngine class 中,它主要用于设置相机。因此,在我的 VC 中,我只需执行 cameraEngine.setup() 即可为我们完成一切。 这是捕获函数:

class CameraEngine: NSObject {

private var capturedImageData: Data?
...

    func captureImage() {
        let settings = AVCapturePhotoSettings()
        photoOutput?.capturePhoto(with: settings, delegate: self)
        print(capturedImageData)
    }

...

}
extension CameraEngine: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        self.capturedImageData = photo.fileDataRepresentation()
    }
}

问题是,如何将委托接收到的值传递给函数并通过完成处理程序返回给 VC?

然后像这样拜访我的 VC cameraEngine.captureImage()

我希望取回数据,以便我可以从我的 VC 中操作它。

您可以将完成块作为参数添加到 captureImage 方法。将其分配给 CameraEngine 引擎 class 的 completion 参数。收到 photoOutput 后,您可以使用此完成块。方法如下:

class CameraEngine: NSObject {

    private var capturedImageData: Data?
    //...
    var completion: ((Data?) -> Void)?
    func captureImage(completion: @escaping (Data?) -> Void) {
        self.completion = completion
        //...
    }
    //...
}
extension CameraEngine: AVCapturePhotoCaptureDelegate {
    func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
        completion?(photo.fileDataRepresentation())
    }
}

用法:

let cameraEngine = CameraEngine()
cameraEngine.captureImage { data in
    print(data)
}