Chapter 39 Landscape artwork resize

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)

Personally, my (general) motto is that if it works for you, then that is the correct solution :smiley: But I realize that if you are starting out in development, or with a specific programming language, sometimes it doesn’t feel like it …

I don’t correctly remember the exact exercise right now but I believe there are several discussions on this forum under the “MyLocations: p.253 exercise aspect fill thumbnails” heading which discuss this particular exercise as well. If you are interested, you can take. a look at those to see other approaches …

1 Like

Thanks Fahim, I’ll check out the other postings.

Absolutely, I understand how things should go together but the idea that there’s more than one correct way to resolve an issue is both an exciting and daunting prospect at the same time. However, I’m sure confidence will come with practise and experience :smile:

This topic was automatically closed after 166 days. New replies are no longer allowed.