【问题标题】:Firebase Storage getData loads image out of order in collectionViewFirebase Storage getData在collectionView中乱序加载图像
【发布时间】:2017-11-18 06:47:58
【问题描述】:

我一直在开发一个照片存储应用程序,它从我的 Firebase 数据库中获取图像链接,将它们按顺序存储在一个数组中,然后运行该数组,使用数组中的链接从相应的 Firebase 存储中获取图像.

但是,即使代码按顺序通过链接运行,getData 函数也会无序加载图像。我不确定为什么会发生这种情况,尽管我最初的想法是图像按大小顺序加载/加载时间最短。这是我的代码。

for link in Constants.officialLinksArray {
        let storage = Storage.storage().reference(forURL: link)

        // Download the data, assuming a max size of 1MB (you can change this as necessary)
        storage.getData(maxSize: 10 * 1024 * 1024) { (data, error) -> Void in
        // Create a UIImage, add it to the array
        if let error = error {
            print(error)
        } else {
            //print(self.imageCount)
            let loadedImage = UIImage(data: data!)
            self.photoArray.append(loadedImage!)
            Constants.officialPhotoArray = self.photoArray
            self.buttonArray.append(self.photoArray.count)
            self.collectionView.reloadData()
            //print(self.photoArray)

        }

    }
}

感谢任何帮助。谢谢!

【问题讨论】:

标签: ios swift firebase firebase-storage


【解决方案1】:

关于为什么您的负载没有考虑到您的数组顺序,我认为(但您需要检查)getData 方法是异步

意思是,当你遍历你的链接数组时,你告诉使用给定的链接执行 getData 方法,但你的循环不会等到你的图像的第一次加载完成后才转到下一个链接。

为了说明我的目的,请在 else 语句中进行打印(加载完成的地方),并在闭包之外但最后在循环内部进行另一个打印。我想你会看到一些关于你的代码执行的有趣行为。

总而言之,如果 getData 是异步的,则基本上您获得的第一个图像是第一个加载的,而不是数组顺序中的第一个。首次加载的原因有很多,计算过程中网络的大小、网络质量、数据库的可用性等。这就是为什么你的图像会变得混乱。

【讨论】:

  • 我明白了。这就是我怀疑发生的事情。有什么方法可以等待第一张图片加载后再获取下一张?
  • 你可以使用完成块,这里是一个例子:stackoverflow.com/questions/43388608/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多