iOS - 如何使用全部列表按顺序下载文件



我是Firebase的新手,正在尝试从文件夹中下载所有图像,同时尝试将它们保持在URL数组中的顺序。

我使用函数listAll获取包含所有图像的引用数组,然后遍历它们,下载 URL 并将它们插入itemImagesURL数组中。当我们循环遍历所有图像后,使用completionHandler返回数组。

这样做的主要问题是数组以错误的顺序填充图像,因为每个项目都不需要相同的时间来下载 url(并将其附加到数组中(。

有没有办法下载每个项目的URL,保持result.items引用数组的原始顺序?

我的代码如下:

func getItemImages(completionHandler: @escaping ([URL?]) -> Void) {
var itemImagesURL: [URL] = []
// We retrieve all images using listAll
downloadRef.listAll(completion: { result, error in
if let error = error {
print("Error listing item images: ", error.localizedDescription)
return
}
itemImagesURL.reserveCapacity(result.items.count)
// We download every image's url
for index in 0 ..< result.items.count {
result.items[index].downloadURL(completion: { url, error in
if let error = error {
//Handle any errors
print("Error downloading item image: ", error.localizedDescription)
return
} else {
// Get download URL
itemImagesURL.insert(url!, at: index)
// All the urls of the item's images are retrieved -> we escape
if itemImagesURL.count == result.items.count {
print("Item's Images download finished.")
completionHandler(itemImagesURL)
}
}
})
}
})  // list all
}

}

这里有一个想法。我通常发现我想与图像一起存储其他东西,例如图像名称,图像本身,发布日期等,因此我喜欢有一个类来保存这些项目。

class ImageInfoClass {
var name = ""
var url = "some url"
var index: Int!
var image: Image()
}

然后存储它们的数组 - 可以用作表视图的数据源。

var myImageArray = [ImageInfoClass]()

然后从存储中读取它们...读入最后一个后,按索引排序即可设置。

func loadImagesAndSort() {
for (index, imageUrl) in result.items.enumerated() {
//perform download
// for each image that's downloaded, create a ImageInfoClass object
//   and populate with the image, the index and a image name for example
let imageInfo = ImageInfoClass()
imageInfo.name = name
imageInfo.index = index
imageInfo.image = //the image
self.myImageArray.append(imageInfo)
if index == lastImageIndex {
self.myImageArray.sort(by: { $0.index < $1.index})
//print to show they are sorted
self.myImageArray.forEach { print($0.index, $0.name)}
}
}
}

最新更新