从异步调用返回图像 [英] Return image from asynchronous call
问题描述
我有一个选择器视图,其中包含图像作为可滚动项.我需要从数据库中提取这些图像,所以出现了Unexptected non-void return value in void function
错误.这是我的代码:
I have a picker view that has images as it's scrollable items. I need to pull those images from my database so I'm getting the Unexptected non-void return value in void function
error. Here is my code:
func pickerView(_ pickerView: AKPickerView, imageForItem item: Int) -> UIImage {
let imgRef = FIRStorage.storage().reference().child("profile_images").child(pets[item])
imgRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data!)
return pic
}
}
所以我理解为什么这行不通,但是我很难找出解决此问题的最佳方法.我能想到的一种解决方案是,将图像设置为一些通用照片,直到发生回调,然后将选择器视图的图像更新为检索到的图像.但是,我不知道如何访问各个选择器视图项以更新其图像.
So I understand why this doesn't work but I'm having a hard time finding out what's the best way to get around this. One solution I can think of is to just set the images to some generic photo until the callback happens, then update the picker view's image to the retrieved image. However, I don't know how to access individual picker view items in order to update its image.
如果任何有经验的人可以给我一些建议,以实现我如何通过异步调用将这些项目设置为数据的目标,我将不胜感激!
If anybody with some experience can give me advice on how I can achieve my goal of setting these items to the data from an asynchronous call I'd greatly appreciate it!
推荐答案
您的函数是一个异步函数.在这种情况下,您必须使用回调.您可以通过以下方式重写该函数以获得所需的结果.
Your function here is an asynchronous function. You have to make use of callbacks in this case. You can rewrite the function in the following way to achieve desired results.
func pickerView(_ pickerView:AKPickerView, imageForeItem item:Int, completion:(_ resultImg: UIImage)->Void) {
let imgRef = FIRStorage.storage().reference().child("profile_images").child(pets[item])
imgRef.data(withMaxSize: 1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
if let pic:UIImage = UIImage(data: data!) {
completion(pic)
}
}
}
可以这样称呼:
self.pickerView(pickerView, imageForeItem: 0) { (image) in
DispatchQueue.main.async {
// set resulting image to cell here
}
}
可以随时提出修改建议,以改善此问题:)
Feel free to suggest edits to make this better :)
这篇关于从异步调用返回图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!