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

Time:01-06

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?

CodePudding user response:

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.

CodePudding user response:

If you are have minimum support version of iOS 13 and using Xcode 13.2, you can use async and await to achieve this:

func loadImages() {
    Task {
        async let firstImage = loadImage(index: 1)
        async let secondImage = loadImage(index: 2)
        async let thirdImage = loadImage(index: 3)
        let images = await [firstImage, secondImage, thirdImage]
    }
}

func loadImage(index: Int) async -> UIImage {
    let imageURL = URL(string: urlPathString)!
    let request = URLRequest(url: imageURL)
    let (data, _) = try! await URLSession.shared.data(for: request, delegate: nil)
    print("Finished loading image \(index)")
    return UIImage(data: data)!
}

Source: SwiftLee: Async let explained: call async functions in parallel

  •  Tags:  
  • Related