Created
September 26, 2017 20:45
-
-
Save gungorbasa/a9cb8f6129936bd18623e59af25b73ac to your computer and use it in GitHub Desktop.
This file contains hidden or 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
import UIKit | |
extension UIImageView { | |
func downloadImageAsync(urlString: String, defaultImage: UIImage, success: @escaping ()->(), failure: @escaping ()->()) { | |
if let image = ImageCache.shared.get(key: urlString) { | |
self.image = image | |
} else { | |
// We can set default image here | |
self.image = defaultImage | |
DispatchQueue.global().async (execute: { | |
guard let url = URL(string: urlString) else { | |
DispatchQueue.main.sync(execute: { | |
failure() | |
}) | |
return | |
} | |
guard let data = try? Data(contentsOf: url) else { | |
DispatchQueue.main.sync(execute: { | |
failure() | |
}) | |
return | |
} | |
guard let image = UIImage(data: data) else { | |
return | |
} | |
ImageCache.shared.set(key: urlString, image: image) | |
DispatchQueue.main.sync (execute: { | |
self.image = image | |
success() | |
}) | |
}) | |
} | |
} | |
func downloadImageAsync(url: String) { | |
self.downloadImageAsync(urlString: url, defaultImage: UIImage(), success: { | |
}, failure: { | |
}) | |
} | |
func downloadImageAsync(url: String, defaultImage: UIImage) { | |
self.downloadImageAsync(urlString: url, defaultImage: defaultImage, success: { | |
}, failure: { | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment