gpt4 book ai didi

ios - Return 函数内部为 Void

转载 作者:行者123 更新时间:2023-11-28 11:05:10 25 4
gpt4 key购买 nike

我正在尝试创建一个用于点击图片的自定义类。在其中,我想创建一个返回 UIImageclickPicture 函数。但是,captureStillImageAsynchronously 是一个 void。我怎样才能返回我从中收到的图像?谢谢。

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.

您不能从包含异步任务的方法返回任何内容。
你需要一个完成 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)

})
}

并这样调用它:

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

关于ios - Return 函数内部为 Void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38160959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com