Created
April 8, 2018 03:12
-
-
Save mitulmanish/de2fd89db237a1c669a7afccf3dc9c7a to your computer and use it in GitHub Desktop.
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
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