0

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!

Hugo Zhang
  • 67
  • 1
  • 9
  • 1
    Instead of downloading image here do it in cellforrow with Asynchronously and for more info refer this: https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift – Dharmesh Kheni Nov 18 '17 at 06:58

1 Answers1

1

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.

Arrabidas92
  • 1,113
  • 1
  • 9
  • 20
  • I see. That's what I suspected was happening. Is there any way to wait for the first image to load before getting the next one? – Hugo Zhang Nov 18 '17 at 23:07
  • You can use a completion block here is an example : https://stackoverflow.com/questions/43388608/how-to-make-synchronous-operation-with-asynchronous-callback – Arrabidas92 Nov 19 '17 at 09:09