Return 函数内部无效

Void Inside of Return function

我正在尝试创建用于点击图片的自定义 class。在其中,我想创建一个 clickPicture 函数,该函数 return 是 UIImage。但是,captureStillImageAsynchronouslyvoid。我怎样才能 return 我从那里收到的图像?谢谢。

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
}

这是在 展开可选 时发现意外的 nil 之后未被挑战的 #2 Swift 问题。

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

capture still image asynchronously.

您不能 return 来自包含异步任务的方法的任何内容。
您需要一个完成块:

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
   } 
}