Search code examples
swiftxcodeimagetableviewcollectionview

How can I download an array of url images from the web


Using regular expressions, I extracted the html string, the desired images and put them in an array.

What does the array look like at the moment:

var collectionPhotoLinks = [
        "http:static-cdn3.vigbo.tech/u65463/78125/blog/5162255/4423863/57114004/500-codleto-889a051259ba894edee37b8da63ddbe9.jpg",
        "http:static-cdn3.vigbo.tech/u65463/78125/blog/5162255/4423863/57114004/500-codleto-9516ab3514e07bde176f117e70c7ba85.jpg"]

I can upload one image

func downloadImages () {

    guard let url = URL(string:
        "http:static-cdn3.vigbo.tech/u65463/78125/blog/5162255/4423863/57114004/500-codleto-889a051259ba894edee37b8da63ddbe9.jpg")
            else { return }

    URLSession.shared.dataTask(with: url) { (data, response, error) in

        if let data = data, let image = UIImage(data: data) {
            DispatchQueue.main.async {

                self.imageView.image = image

            }
        }
    } .resume()
}

If the "url" is replaced with an array "collectionPhotoLinks", then respectively xcode requires string not array

So the question follows, how do I load all the images from the array? In the future I will need to send them to tableview or collectionview, but I would like to resolve the issue with this first.


Solution

  • The usual is that you download it inside cellForRowAt with say SDWebImage , but if you need to pre-download all then you can try

    let arr = ["url1","urls"]
    
    func downloadImages () {
    
        let g = DispatchGroup()
    
        for item in arr {
    
            guard let url = URL(string:item)
                    else { return }
    
            g.enter()
    
            URLSession.shared.dataTask(with: url) { (data, response, error) in
    
                if let data = data, let image = UIImage(data: data) {
    
                    //
                }
    
                g.leave()
    
            } .resume()
        }
    
        g.notify(queue: .main) {
    
            // done 
        }
    
    }