简体   繁体   中英

Void Inside of Return function

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM