问题
I am trying to create a custom class for clicking pictures. Inside of it, I would like to create a clickPicture
function that returns a UIImage
. However, the captureStillImageAsynchronously
is a void
. How can I return the image I receive from that? Thanks.
func clickPicture() -> UIImage? {
if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) {
videoConnection.videoOrientation = .portrait
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in
if sampleBuffer != nil {
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
let dataProvider = CGDataProvider(data: imageData!)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right)
return image //Unexpected non-void return value in void function
}
return nil //Unexpected non-void return value in void
})
}
return nil
}
回答1:
That's the unchallenged #2 Swift question after unexpected nil found while unwrapping an optional.
The method describes pretty well what is does :
capture still image asynchronously.
You cannot return anything from a method which contains an asynchronous task.
You need a completion block:
func clickPicture(completion:(UIImage?) -> Void) {
guard let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo) else { completion(nil) }
videoConnection.videoOrientation = .portrait
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: { (sampleBuffer, error) -> Void in
guard let buffer = sampleBuffer else { completion(nil) }
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
let dataProvider = CGDataProvider(data: imageData!)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: .defaultIntent)
let image = UIImage(cgImage: cgImageRef!, scale: 1, orientation: .right)
completion(image)
})
}
and call it this way:
clickPicture { image in
if unwrappedImage = image {
// do something with unwrappedImage
}
}
来源:https://stackoverflow.com/questions/38160959/void-inside-of-return-function