Skip to content

Instantly share code, notes, and snippets.

@dimpiax
Last active October 31, 2016 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimpiax/a2e523d8523a68b90c62a31e822f2507 to your computer and use it in GitHub Desktop.
Save dimpiax/a2e523d8523a68b90c62a31e822f2507 to your computer and use it in GitHub Desktop.
Get remote or default image
// somewhere in your class
// where you have declared instance of UIImageView as _imageView
func test() {
UIImage.getRemote(path: "path_to_image", default: "image_name") {[weak self] value in
DispatchQueue.main.async {[weak self] in
guard let s = self else { return }
s._imageView.image = value
s._imageView.sizeToFit()
}
}
}
...
extension UIImage {
class func getRemote(path: String, default defaultName: String, completion: @escaping (UIImage?) -> Void) {
load(path: path) { value in
var image = value
if image == nil {
image = UIImage(named: defaultName)
}
completion(image)
}
}
class func load(path: String, completion: @escaping (UIImage?) -> Void) {
guard let url = URL(string: path) else {
return completion(nil)
}
let urlSession = URLSession(configuration: URLSessionConfiguration.default)
let task = urlSession.dataTask(with: url) { data, urlResponse, error in
guard let data = data, let image = UIImage(data: data) else {
completion(nil)
return
}
completion(image)
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment