Kingfisherというライブラリを使ってみました。
こちらはSDWebImageにインスパイアされて作ったもので、画像のダウンロードが簡単にできるものになっています。
インストール
いつものようにCocoapodsを使います。
target 'MyApp' do use_frameworks! pod 'Kingfisher' end
使い方
以下のように画像の読み込みを行う事ができます。
import UIKit import Kingfisher class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let v = UIImageView(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) v.kf.setImage(with: URL(string: "https://cdn-ak.f.st-hatena.com/images/fotolife/l/llcc/20151012/20151012161841.png")) view.addSubview(v) } }
実行すると以下のように画像が表示されます。
setImageにはプレースホルダー画像、完了後のコールバックなどを渡す事ができます。
import UIKit import Kingfisher class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let v = UIImageView(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) v.kf.setImage(with: URL(string: "https://cdn-ak.f.st-hatena.com/images/fotolife/l/llcc/20151012/20151012161841.png"), placeholder: #imageLiteral(resourceName: "placeholder"), options: nil, progressBlock: { receivedSize, totalSize in }, completionHandler: { image, error, cacheType, imageURL in }) view.addSubview(v) } }
オプションではキャッシュ方法やScaleなどを設定できます。
形式は、以下enumの配列になります。
public enum KingfisherOptionsInfoItem { case targetCache(ImageCache) case downloader(ImageDownloader) case transition(ImageTransition) case downloadPriority(Float) case forceRefresh case forceTransition case cacheMemoryOnly case onlyFromCache case backgroundDecode case callbackDispatchQueue(DispatchQueue?) case scaleFactor(CGFloat) case preloadAllGIFData case requestModifier(ImageDownloadRequestModifier) case processor(ImageProcessor) case cacheSerializer(CacheSerializer) case keepCurrentImageWhileLoading }
setImageにはUIButtonにも追加されています。
こちらは引数にUIControlStateを渡す必要があります。
import UIKit import Kingfisher class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let b = UIButton(frame: CGRect(x: 10, y: 10, width: 100, height: 100)) b.kf.setImage(with: URL(string: "https://cdn-ak.f.st-hatena.com/images/fotolife/l/llcc/20151012/20151012161841.png"), for: .normal, placeholder: #imageLiteral(resourceName: "placeholder"), options: nil, progressBlock: { receivedSize, totalSize in }, completionHandler: { image, error, cacheType, imageURL in }) view.addSubview(b) } }