I want to create UIImage(urlString: String?)
. There is no error when I run this code but it is not working.
extension UIImage {
convenience init?(urlString: String?) {
var imageData = Data()
guard let urlString = urlString else { return nil}
guard let url = URL(string: urlString) else { return nil}
URLSession.shared.dataTask(with: url) { data, response, error in
if let error = error {
print("Error: (error.localizedDescription)")
return
}
guard let response = response as? HTTPURLResponse else {
print("Empty image response")
return
}
print("HTTP image response code: (response.statusCode)")
guard let data = data else {
print("Empty image data")
return
}
imageData = data
}.resume()
self.init(data: imageData)
}
}
2
Answers
UIImage
initializerinit(data:)
is a synchronous method. Yourself.init(data: imageData)
method is called before the async methoddataTask
finish its request and execute its completion handler.What I suggest is to create an instance method extending
URL
and add a completion handler to it:Usage:
Another option is to extend UIImageView as shown in this post
My solution for you:
You have to call self.init() because it required self.init() to be called before return.
Because this is a Failable Initializer, if your URL is valid then you get an image from that URL, otherwise, you get nil.
In case you want to use a default image when your URL is invalid, just replace init() with init(named:):