如何在swift 5中保持回调函数外的数据



我是swift的新手,目前正在开发一个应用程序,需要下载我存储在firebase云存储上的图像。我遇到的一个问题是,我试图使用firebase文档中的代码直接下载它,您可以在下面看到。

// Create a reference to the file you want to download
let islandRef = storageRef.child("images/island.jpg")
// Download in memory with a maximum allowed size of 1MB (1 * 1024 * 1024 bytes)
islandRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
if let error = error {
// Uh-oh, an error occurred!
} else {
// Data for "images/island.jpg" is returned
let image = UIImage(data: data!)
}
}

但正如你所看到的,image属性似乎在这个闭包中丢失了,但很明显,我希望能够使用该图像,并将其设置为我的应用程序中imageview的图像属性。我想知道我能做些什么,让该图像在.getData 的回调函数之外持续存在

您可以使用这个:

let Ref = Storage.storage().reference(forURL: imageUrlUrl)
Ref.getData(maxSize: 1 * 1024 * 1024) { data, error in
if error != nil {
print("Error: Image could not download!")
} else {
yourImageView.image = UIImage(data: data!)
}
}

希望它能帮助。。。

最新更新