Reputation: 67
I've been developing a photo storage app that gets the image links from my Firebase database, stores them in an array in order, and then run through that array getting the images from the corresponding Firebase storage using the links in the array.
However, the function getData loads the images out of order even though the code runs through the links in order. I am not sure why this is happening although my initial thought was that the images load in order of size/which takes the least time to load. Here's my code.
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)
}
}
}
Any help is appreciated. Thanks!
Upvotes: 0
Views: 1394
Reputation: 1153
About why your loads is not taking into account your array order, I think (but you need to check) that the getData
method is asynchronous.
Meaning, when you loop through your link array you tell to execute the getData method with the given link but your loop is not waiting until the first load of your image is done to go to the next link.
To illustrate my purpose, make a print inside your else statement (where your load is finish) and another print outside of your closure but inside your loop at the end. I think you will see some interesting behaviour about your code execution.
To conclude, if getData is asynchronous, basically the first images you get are the first loaded and not the first in your array order. First loaded because of the size, quality of network during computation, availability of the database, many reasons. That's why you get your images in disorder.
Upvotes: 1