Has anyone else managed to do the image resize exercise at the end of the chapter 39?
I think I have the solution, and it seems to work on different simulators, but I don’t know if I’m overlooking anything or have missed something and it doesn’t actually work.
I reused the UIImage+Resize.swift code and then called it in the downloadImage method after unwrapping the button and then set the height and width to the bounds of the button.
Could any one please confirm this is correct or how it should’ve been done.
Thanks in advance
private func downloadImage(for searchResult: SearchResult, andPlaceOn button: UIButton) {
if let url = URL(string: searchResult.imageSmall) {
let task = URLSession.shared.downloadTask(with: url) {
[weak button] url, response, error in
if error == nil, let url = url,
let data = try? Data(contentsOf: url),
let image = UIImage(data: data) {
DispatchQueue.main.async {
if let button = button {
button.setBackgroundImage(image.resized(withBounds: CGSize(width: button.bounds.width, height: button.bounds.height)), for: .normal)
}
}
}
}
task.resume()
downloads.append(task)
}
}