gpt4 book ai didi

ios - 在不使用实时数据库的情况下使用 while 循环从 Firebase 存储检索和加载图像?

转载 作者:行者123 更新时间:2023-11-30 12:02:06 25 4
gpt4 key购买 nike

我现在正在 Swift 中开发一个照片库应用,使用 Firebase 来存储图像。我的目标是在加载 View 时加载 Collection View 中的所有图像。

图像存储在名为 images_(用户电子邮件)_(用户 ID) 的文件夹中。用户上传的图像存储在 Firebase 存储中,名称为 image0.png、image1.png、image2.png 等。现在,我已成功创建帐户并存储图像。现在,我尝试在 viewDidLoad() 的 Collection View 中加载图像。我没有使用 Firebase 实时数据库,因为我觉得它对于我想要完成的任务来说有点过分了。

while (isDownloading == true) {

let storage = Storage.storage()
let storageRef = storage.reference();
let imageLoadRef = storageRef.child(("images_" + (Auth.auth().currentUser?.email)! + "_" + (Auth.auth().currentUser?.uid)!) + "/image" + String(self.imageCount) + ".png")

imageLoadRef.getData(maxSize: 10 * 1024 * 1024) { data, error in
if let error = error {
self.isDownloading = false
} else {
let loadedImage = UIImage(data: data!)

//Updates collection view with loaded image
self.collectionView.reloadData()

//moves on to next image
self.imageCount += 1
}
}
}

一旦 View 加载,我就会运行一个 while 循环来迭代用户文件夹中的所有图像。由于我没有任何方法来获取文件夹中的图像数量,因此我不得不使用 while 循环并在找不到下一个图像时中断它。例如,如果文件夹中只有 5 个图像,则代码在尝试加载第六个不存在的图像时将返回错误。发生这种情况时,我 try catch 错误并通过将条件 isDownloading 设置为 false 来中断 while 循环。

但是,我遇到的问题是 while 循环永远不会中断,即使它应该返回错误并将 isDownloading 设置为 false。

为了澄清,imageCount 变量随着 while 循环的每次迭代而增加,以获取文件夹中的下一个图像。例如,当 imageCount = 1 时,代码将尝试加载名为“image1.png”的照片。但是,如果它不存在,它会捕获错误并中断 while 循环。

我知道我的结构方式有点令人困惑,但我发现它比使用 downloadURL 和 Firebase 数据库更有效。

感谢任何帮助。谢谢!

最佳答案

不知道它是否有效,您可以暂时尝试一下,如果存在问题请告诉我

//Loop is Fine
while (isDownloading == true) {
//Provided Required References
let storage = Storage.storage()
let storageRef = storage.reference();
//Name of file to download
let imageLoadRef = storageRef.child(("images_" + (Auth.auth().currentUser?.email)! + "_" + (Auth.auth().currentUser?.uid)!) + "/image" + String(self.imageCount) + ".png")
//handler That Run in async Mode
imageLoadRef.getData(maxSize: 10 * 1024 * 1024) { data, error in
//Here I think mistake is
if let error = error {
//You are catching error But not handling data error
self.isDownloading = false
}
else {
if data != nil{ // if image found
//here you need to check weather this handler is returning data o not as you got error of no data So Do All functioning here
// User photo here
let loadedImage = UIImage(data: data!)

//Updates collection view with loaded image
self.collectionView.reloadData()

//moves on to next image
self.imageCount += 1
}
else {
//If Image is not found This will cause you an error which you will handle , According to me this was need to be handled
self.isDownloading = false
}

}
}
}

如果此解决方案不起作用,您可以查看 GitHub 上的以下演示项目,并使用此方法轻松管理存储在用户名下的图像

Link - https://github.com/RockinGarg/FirebaseDemo

关于ios - 在不使用实时数据库的情况下使用 while 循环从 Firebase 存储检索和加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47088510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com