2015-01-04 24 views
0

所以我写了一个本来应该用相机拍照的方法,然后将该照片作为UIImage返回。但是我已经得到这个奇怪的错误Cannot convert the expression's type 'UIImage?' to type 'Void',我不知道什么原因引起的?下面的代码:无法转换表达式的类型'UIImage?'键入'虚空'

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

我看到现在的问题..在'captureStillImageAsynchronouslyFromConnection'通话,返回类型为'Void'。那么我应该如何改变它,以便它返回一个UIImage? – ddolce

回答

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

没错,我还注意到我忘记'captureStillImageAsynchronouslyFromConnection'中的'completionHandler'有一个'Void'返回类型。谢谢你,我会去尝试一下。 – ddolce

相关问题