从 Firebase 检索图像到 UIimage swift5

Retrieve an image from Firebase to an UIimage swift5

我正在努力将图片从 firebase 存储下载到 swift 中的 UIImage 5.

我可以很好地上传它们。当我尝试检索图片时,UIImage 显示黑屏。

这里是我的函数,其中 return UIImage

import UIKit

import Firebase

func getImageEvent (imagePath : String) -> UIImage? {

    var myImage : UIImageView?

    //Access to the storage
    let storageRef =  Storage.storage().reference(withPath: imagePath)

    storageRef.getData(maxSize: 1 * 1024 * 1024) {(data, error) in

        if let error = error {
            print(error.localizedDescription)
            return
        }

        if let data = data {

            print(data.description)

            myImage?.image = UIImage(data: data)

        }
    }

    return myImage?.image
}

//Call the function

getImageEvent (imagePath :"9U4BoXgBgTTgbbJCz0zy/eventMainImage.jpg")

在控制台中,我可以很好地看到 print(data.description) 的值。

默认情况下,UIImageView中有一张图片。调用该函数时,默认图像被黑屏取代。

你能帮我理解错误吗?

非常感谢

有多种方法可以解决这个问题,但首先要简要说明问题:

闭包中的 return 语句将在下载图像之前执行 - Firebase 函数是异步的,并且必须以允许有时间从 Internet 下载和获取数据的方式编写代码。所以 - 不要尝试 return 来自异步函数的数据。

这是使用完成处理程序重写的代码。只有在图像完全下载后才会调用该处理程序。

func getImageEvent (imagePath: String, completion: @escaping(UIImage) -> Void) {
    var myImage : UIImageView?
    let storageRef =  Storage.storage().reference(withPath: imagePath)
    storageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if let error = error {
            print(error.localizedDescription)
            return
        }

        if let data = data {
            if let myImage = UIImage(data: data) {
                completion(myImage)
            }
        }
    }
}

关键是如何调用该函数。请注意,此代码等待数据 (UIImage) 在其闭包内传回给它,并让您知道获取图像已完成。

self.getImageEvent(imagePath: "9U4BoXgBgTTgbbJCz0zy/eventMainImage.jpg", completion: { theImage in
    print("got the image!")
})

您应该添加额外的错误检查以防图像未下载或 myImage 为 nil。将错误消息与 nil myImage 一起传回是一种选择,或者将对象作为可选对象传回,然后在 self.downloadImageAtPath 内检查 nil 将是另一种选择。

为了完成解决方案,下面是用于在 tableView 中获取特定单元格中的图片的代码

 getImageEvent(imagePath: myArray[indexPath.row].partyImagePath) { (image) in

         cell.partyImage.image = image

        }