从Firebase检索图像到UIimage swift5

问题描述 投票:0回答:2

我正在努力将图片从Firebase存储下载到Swift 5中的UIImage。

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

这里是我的返回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中有一个图像。调用该函数时,默认图像将被黑屏取代。

您能帮我理解错误吗?

非常感谢

swift firebase uiimage firebase-storage
2个回答
0
投票

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

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

         cell.partyImage.image = image

        }

0
投票

有许多解决方法,但首先对此问题进行简要说明:

闭包中的return语句将在下载映像之前执行-Firebase函数是异步的,必须以允许时间从Internet下载和获取数据的方式来设计代码。因此-不要尝试从异步函数返回数据。

这是用完成处理程序重写的代码。仅在完全下载映像后,该处理程序才会被调用。

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将是另一种选择。

© www.soinside.com 2019 - 2024. All rights reserved.