Last active
October 27, 2018 14:06
-
-
Save marcos1262/8b7cfa7c95eb79f39ec915af3e7f94eb to your computer and use it in GitHub Desktop.
Asynchronous download of images and saving in caches directory
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 { | |
//Use this function with the imageview | |
func loadImageUsingCacheWithUrlString(_ url: String?) { | |
guard let url = url else { | |
self.image = UIImage(named: "default") | |
return | |
} | |
let imageName = url.split(separator: "/").last! as NSString | |
let fileManager = FileManager.default | |
let diskPaths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) | |
let cacheDirectory = diskPaths[0] as String | |
let diskPath = cacheDirectory.appending(imageName as String) | |
//check cache for image first | |
if fileManager.fileExists(atPath: diskPath) { | |
self.image = UIImage(contentsOfFile: diskPath) | |
return | |
} | |
//otherwise fire off a new download | |
URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: { (data, response, error) in | |
guard error == nil else { | |
print("Image download error:", error?.localizedDescription ?? "") | |
return | |
} | |
DispatchQueue.main.async { | |
if let data = data, let image = UIImage(data: data) { | |
try? data.write(to: URL(fileURLWithPath: diskPath), options: .atomic) | |
self.image = image | |
} | |
} | |
}).resume() | |
} | |
} | |
extension UIImageView { | |
func downloadedFrom(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) { | |
contentMode = mode | |
URLSession.shared.dataTask(with: url) { (data, response, error) in | |
guard | |
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, | |
let mimeType = response?.mimeType, mimeType.hasPrefix("image"), | |
let data = data, error == nil, | |
let image = UIImage(data: data) | |
else { return } | |
DispatchQueue.main.async() { | |
self.image = image | |
} | |
}.resume() | |
} | |
func downloadedFrom(link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) { | |
guard let url = URL(string: link) else { return } | |
downloadedFrom(url: url, contentMode: mode) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
By @guilhermecolombini