'Downloading multiple images from url in swift ui

In my app i am using firebase as a backend for storing data and there's a case where i have to upload multiple images as a preview images to firebase which works fine but when i download those images using the url that i am storing in my model, it appears in random order i.e image 2 downloads first before image 1 and so on.. how do i resolve this. In selectedPreviewImages array the images are random everytime

This is the download function i am using:

func downloadImage(with link: String,
                       completionHandler: @escaping (_ image: UIImage?) -> ()) {
        guard let url = URL(string: link) else { return }
        
        DispatchQueue.global().async {
            if let data = try? Data(contentsOf: url) {
                if let image = UIImage(data: data) {
                    DispatchQueue.main.async {
                        completionHandler(image)
                    }
                }
            }
        }
    

}

Sharing my code snippet:

if let item = selectedItem { 
    let tmpLinks = item.displayPreviewImageLinks.sorted()

            print("Preview Image Links ==> \(tmpLinks)")

            if tmpLinks.count > 0 {
                for link in tmpLinks {
                    ImageDownloader.shared.downloadImage(with: link, completionHandler: { [weak self] image, _ in
                        
                        guard let self = self else { return }
                        self.showProgress = false
                        
                        if image != nil {
                            self.selectedPreviewImages.append(image!)
                        }
                    }, placeholderImage: nil)
                }
            } else {
                self.showProgress = false
            }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source