Based on https://stackoverflow.com/a/27712427/4166655, I found that I can create a UIImage
with this code
func downloadImage(from url: URL) {
print("Download Started")
getData(from: url) { data, response, error in
guard let data = data, error == nil else { return }
print(response?.suggestedFilename ?? url.lastPathComponent)
print("Download Finished")
DispatchQueue.main.async() {
self.imageView.image = UIImage(data: data)
}
}
}
I saw many UIImageView
extensions incorporating this code, but I wondered if I could make this work as a direct init for UIImage
.
I came up with this —
extension UIImage {
convenience init?(url: String) {
guard let urlObj = URL(string: url) else { return nil }
self.init(url: urlObj)
}
convenience init?(url: URL) {
let semaphore = DispatchSemaphore(value: 0)
var imageData: Data? = nil
URLSession.shared.dataTask(with: url) { (data, response, err) in
// breakpoint put here
guard let data = data else { return }
imageData = data
semaphore.signal()
}
semaphore.wait()
if let data = imageData {
self.init(data: data)
} else {
return nil
}
}
}
But this just times out, and my breakpoint (noted in the code) never triggers.
What's wrong with this approach?