如何从Firebase-storage下载图像以显示在collectionViewCell的Imageview(Swift)中



我已经将图像上传到Firebase-storage中,并将downloadURL保存到数据库内的键/值对中。我编写了一个代码,假设在检索数据后,如果 url 有效,则在 collectionView 中显示图像。该代码在cellForItemAt 执行,因为包含图片的集合视图嵌入在另一个集合视图(将称为 Main 或 MainCV 以防止混淆(中。

为了解决这个问题,我尝试在 MainCV 中重新加载集合视图的数据,并尝试仅使用 ImageView 在视图控制器上测试代码(不成功(。

// function to display images
private func icon(_ imageURL: String) -> UIImage {
//print("imageURL is (imageURL)")
let url = URL(string: imageURL)
var image: UIImage?
var imageData:Data?
if url == nil {
print("URL is (imageURL)")
return #imageLiteral(resourceName: "ic_person_outline_white_2x")
} else {
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("error")
return
}
DispatchQueue.main.async {
imageData = data
image = UIImage(data: imageData!)
}
}.resume()
return image ?? #imageLiteral(resourceName: "ic_person_outline_white_2x")
}
}

CellForItemAt 代码块

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! ImageCell
let imageOption = self.imageData[indexPath.row]
cell.iconImageView.image = icon(imageOption)
return cell
//imageData is an array with empty values that is populated with database values and subsequently reloaded
}

正如我之前所说,预期的结果是在collectionView中显示来自firebaseStorage的图像。我的代码不会呈现任何错误,但始终返回默认图像以及打印 imageURl,我确认它是我尝试显示的图像的准确 http。

你需要学习一些关于异步编程的知识。

您的函数会立即返回,但URLSession.shared.dataTask(with: url!)需要一些时间。时间轴:

  1. 图像 = 无
  2. 开始获取数据
  3. 返回图像?? 默认图像
  4. 获取数据完成(函数返回后 ->图像数据丢失(

不要立即返回,而是在函数中提供闭包图像作为参数:

private func icon(_ imageURL: String, closure: (UIImage) -> Void)

并将您的代码更新为

URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("error")
closure(#imageLiteral(resourceName: "ic_person_outline_white_2x"))
}
DispatchQueue.main.async {
imageData = data
image = UIImage(data: imageData!)
closure(image)
}
}.resume()

闭包本身可以是接受图像作为参数并将此图像异步设置为集合视图单元格的函数

此外,您希望在加载图像之前提供一些默认图像或正在加载的图像。或使用活动指示器。

希望这有帮助!

最新更新