Skip to content

Instantly share code, notes, and snippets.

@mitulmanish
Created April 8, 2018 03:12
Show Gist options
  • Save mitulmanish/de2fd89db237a1c669a7afccf3dc9c7a to your computer and use it in GitHub Desktop.
Save mitulmanish/de2fd89db237a1c669a7afccf3dc9c7a to your computer and use it in GitHub Desktop.
enum ImageDownloadError: Error {
case url(errorDescription: String)
case data(errorDescription: String)
}
class CustomImageView: UIImageView {
var downloadTask: URLSessionDataTask?
func loadImageUsing(urlString string: String,
finishedLoadingImage: @escaping (Error?) -> ()) {
guard let url = URL(string: string) else {
finishedLoadingImage(ImageDownloadError.url(errorDescription: "cant construct url using: \(string)"))
return
}
do {
if let imageData = try AssetSaveHelper.cachedDataForTag("\(string.hashValue)") {
self.image = UIImage(data: imageData)
finishedLoadingImage(nil)
return
}
} catch let err {
print(err)
}
downloadTask = URLSession.shared.dataTask(with: url) {
[weak self] (data, response, error) in
guard let httpResponse = response as? HTTPURLResponse,
(200 ... 299).contains(httpResponse.statusCode),
let data = data else {
finishedLoadingImage(ImageDownloadError.data(errorDescription: ""))
return
}
DispatchQueue.main.async { [weak self] in
self?.image = UIImage(data: data)
try? AssetSaveHelper.cacheDataForTag(data, tag: "\(string.hashValue)")
finishedLoadingImage(nil)
}
}
downloadTask?.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment