Search code examples
iosswiftobjective-cuiimageview

iOS - how to show multi network images at the same time?


On my UIView, I have 3 UIImageViews to load 3 image's url. As we all know, 3 UIImageView load images has time difference , But I have a requirement: After 3 images all downloaded, then 3 UIImageViews show these 3 images at the same time, how to do?


Solution

  • So if I understood correctly you want to firstly download all 3 images and only then display them? If so I'd suggest using a DispatchGroup.

    let images: [URL] = []
        let dispatchGroup = DispatchGroup()
        
        for image in images {
            dispatchGroup.enter()
            URLSession.shared.dataTask(with: image) { (data, response, error) in
                // save image data somewhere
                dispatchGroup.leave()
            }.resume()
        }
        
        dispatchGroup.notify(queue: .main) {
            // display images on the image view
        }
    

    Basically what this does is whenever starting a download you enter in a dispatch group and when the download is done you leave it. After every operation left the group you use the notify completion and display what you want.