Void Inside of Return function

梦想的初衷 提交于 2019-12-25 07:13:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!