3

I currently have working code that lets me download a single image. It then puts that image in a imageview inside a collectionview cell.

However, I want to download 2 images from 2 different URLs. Do I need to create another URLSession Task, or can I simply download 2 images with the same session?

let url = URL(string: "www.example.com/image.jpg")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in 
guard let data = data, error == nil else { return }

DispatchQueue.main.async() {
    cell.postImage.image = UIImage(data: data) 
    }
}

Edit: Not sure why Leo marked my question as a duplicate. I already saw that post and it only loads a single image. My questions is in regards to the correct way of downloading multiple images smh.

2
  • my recommendation is to use a extension on your imageview . and there are few good 3rd party libraries that will make it more easy Commented Jan 23, 2018 at 12:44
  • Take a look at LazyTableImages how to use a simple asynchronous download manager. Commented Jan 23, 2018 at 13:09

2 Answers 2

2

I would recommend you to use a third party library for this purpose. What I can suggest is the SDWebImage Library: SDWebImage

The usage of the library is pretty simple. Here is an example:

import SDWebImage

imageView.sd_setImage(with: URL(string: "http://www.test.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

It handles the asynch downloading itself, so you don't need to worry about this stuff anymore. Also it has a clever caching system integrated, that means if the image is downloaded once, it will not download the same image again.

Sign up to request clarification or add additional context in comments.

Comments

1

You want a separate data task per image. Note that whether you have to create a separate data task (you do) is different than whether you need to create a separate URLSession object. (For simple tasks using the shared session object is fine.)

You can also use a 3rd party library like the others are suggesting. There are both pros and cons to using 3rd party frameworks.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.