Last active
October 31, 2016 08:04
-
-
Save dimpiax/a2e523d8523a68b90c62a31e822f2507 to your computer and use it in GitHub Desktop.
Get remote or default image
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
// 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