Last active
June 14, 2019 15:33
-
-
Save noa4021J/11b8bf6b6b0114139869d891e2f9ad4e 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
extension UIImageView { | |
static let imageCache = NSCache<AnyObject, AnyObject>() | |
func setImage(fromUrl: String?) { | |
//URLがnilだった場合はdefaultの画像をセットする | |
guard let urlString = fromUrl else { | |
self.image = UIImage(named: "default") | |
return | |
} | |
//キャッシュされているURLならば、その中から画像を取り出してセットする | |
if let cacheImage = UIImageView.imageCache.object(forKey: fromUrl as AnyObject) as? UIImage { | |
self.image = cacheImage | |
return | |
} | |
let imageUrl = URL(string: urlString) | |
DispatchQueue.global().async { | |
do { | |
//まだ一度も取得していない画像をURLから画像を取得し、キャッシュする | |
let data = try Data(contentsOf: imageUrl!) | |
let image = UIImage(data: data) | |
UIImageView.imageCache.setObject(image!, forKey: fromUrl as AnyObject) | |
DispatchQueue.main.async { | |
self.image = image | |
} | |
} catch let error { | |
//エラーの場合にはdefaultの画像をセットする | |
print("Error : \(error.localizedDescription)") | |
self.image = UIImage(named: "default") | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment