Created
May 10, 2018 18:28
-
-
Save khurram18/1adeda04d5155b5a829f67c4a9aa176b to your computer and use it in GitHub Desktop.
A category for downloading image from URL and display it in UIImageView in iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension UIImageView { | |
static var dataTask: URLSessionDataTask? | |
func download(urlString: String) { | |
guard let url = URL(string: urlString) else { | |
print("\(urlString) is not a valid url") | |
return | |
} | |
if let existingTask = UIImageView.dataTask { | |
if existingTask.state == .running { | |
existingTask.cancel() | |
} | |
} | |
let task = URLSession.shared.dataTask(with: url) { data, response, error in | |
if let error = error { | |
print("An error occured while dowloading image from url \(url) error:\(error)") | |
return | |
} | |
guard let httpResponse = response as? HTTPURLResponse, | |
(200...299).contains(httpResponse.statusCode) else { | |
print("\(response.debugDescription)") | |
return | |
} | |
guard let data = data else { | |
print("data is not valid") | |
return | |
} | |
guard let image = UIImage(data: data) else { | |
print("Cannot create image from data") | |
return | |
} | |
DispatchQueue.main.async { | |
self.image = image | |
} | |
} | |
task.resume() | |
UIImageView.dataTask = task | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment