Void Inside of Return功能

时间:2016-07-02 13:58:08

标签: ios swift function return void

我正在尝试为点击图片创建自定义类。在其中,我想创建一个返回clickPicture的{​​{1}}函数。但是,UIImagecaptureStillImageAsynchronously。如何归还我收到的图像?感谢。

void

1 个答案:

答案 0 :(得分:3)

在解开可选时发现意外的nil后,这是未受质疑的#2 Swift问题。

该方法很好地描述了它的作用:

  

捕捉静止图像异步

您无法从包含异步任务的方法返回任何内容 你需要一个完成块:

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) 

    })
}

并以这种方式称呼它:

clickPicture { image in 
   if unwrappedImage = image {
     // do something with unwrappedImage
   } 
}