I use following function func request(imageURL:completion)
to download images for tableViewCells. As multiple table view cells calls this function simultaneously, how should I make sure downloaded image in URLSession corresponds to which request imageURL?
In my project, when I use resp.url
under URLSession completion block, it has different address of image storage location. So I cannot use that to validate with requested imageURL.
Is there another way so I can store these image in dictionary/cache for correct request imageURL?
class ImageDownloader {
static let shared = ImageDownloader()
private init() { }
var dict = [URL: UIImage]()
func request(imageURL: URL, completion: @escaping (Result<Data, ImageFetchError>) -> Void) {
let dataTask = URLSession.shared.dataTask(with: imageURL) { data, resp, error in
// Response received after random seconds
/*
requestURL = https://picsum.photos/200/300
resp.url = "https://i.picsum.photos/id/621/200/300.jpg?hmac=GgxwZqdPsVQwlM2QhfHoLU8gZ7uo_PP6oD4KmIq-ino"
*/
serverUrl[imageURL] = UIImage(data: data!)
}.resume()
}
}
// This would be repeated in cellForItemAtIndexPath method.
class CustomCell: UICollectionViewCell {
func downloadImage() {
let url = URL(string: model.url) // model.url = "https://picsum.photos/200/300"
ImageDownloader.shared.request(URL(string: url)!) { result in
}
}
}