所以我写了一个应该用相机拍照然后将照片作为UIImage
返回的方法。但是我已经得到了这个奇怪的错误Cannot convert the expression's type 'UIImage?' to type 'Void'
,我不知道是什么导致了它......以下是代码:
func captureAndGetImage()->UIImage{ dispatch_async(self.sessionQueue, { () -> Void in // Update orientation on the image output connection before capturing self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.previewLayer!.connection.videoOrientation if let device = self.captureDevice{ self.imageOutput!.captureStillImageAsynchronouslyFromConnection(self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo), completionHandler: { (imageDataSampleBuffer, error) -> Void in if ((imageDataSampleBuffer) != nil){ var imageData:NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer) var image = UIImage(data: imageData) return image } }) } }) }
我也试过return image as UIImage
,但它也没有用。
我的猜测是与完成处理程序有关。
谢谢!
答案 0 :(得分:0)
问题在于您将此视为同步操作,但它是异步的。您无法从异步操作返回图像。您将不得不重写您的方法以获取完成块,然后在您检索图像时执行该块。我将其重写为以下内容:
func captureAndGetImage(completion: (UIImage?) -> Void) {
dispatch_async(self.sessionQueue, { () -> Void in
// Update orientation on the image output connection before capturing
self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo).videoOrientation = self.previewLayer!.connection.videoOrientation
if let device = self.captureDevice{
self.imageOutput!.captureStillImageAsynchronouslyFromConnection(self.imageOutput!.connectionWithMediaType(AVMediaTypeVideo), completionHandler: { (imageDataSampleBuffer, error) -> Void in
var image: UIImage?
if ((imageDataSampleBuffer) != nil){
var imageData:NSData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
image = UIImage(data: imageData)
}
completion(image)
})
}
})
}