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.

hmzfier
  • 554
  • 9
  • 21
  • my recommendation is to use a extension on your imageview . and there are few good 3rd party libraries that will make it more easy – Kamal Upasena Jan 23 '18 at 12:44
  • Take a look at [LazyTableImages](https://developer.apple.com/library/content/samplecode/LazyTableImages/Introduction/Intro.html) how to use a simple asynchronous download manager. – vadian Jan 23 '18 at 13:09

2 Answers2

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.

Kingalione
  • 4,237
  • 6
  • 49
  • 84
0

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.

Duncan C
  • 128,072
  • 22
  • 173
  • 272