LoginSignup
16
17

More than 5 years have passed since last update.

[Swift]KingFisherで画像URLから画像データをダウンロード

Last updated at Posted at 2016-08-11

KingFisherを利用して、画像URLから画像データ(UIImage型やNSData型)をダウンロードする方法

var images = [UIImage]
var datas = [NSData]

let kf = KingfisherManager.sharedManager.downloader

for file in files {
  kf.downloadImageWithURL(NSURL(string: file.url!)!,
      progressBlock:nil,
      completionHandler: { (image, error, imageURL, originalData) -> () in
        images.append(image)
        datas.append(originalData)
  })
}

 
ちなみに、下記のようにUIImageView.kf_setImageWithURLcompletionHandlerからコールバックする方法では、一度UIImageViewで画像表示され、メモリにキャッシュされた場合のみ、completionHandlerが実行されるみたいで、一度も表示されていない画像についてはcompletionHandlerで画像データを扱うことができないので注意。(結構ハマった)

imageView.kf_setImageWithURL(NSURL(string: "your_image_url")!,
   placeholderImage: nil,
        optionsInfo: nil,
      progressBlock: { (receivedSize, totalSize) -> () in
        print("Download Progress: \(receivedSize)/\(totalSize)")
      },
  completionHandler: { (image, error, cacheType, imageURL) -> () in
    // ★1回表示した画像のみ実行される!
    print("Downloaded and set!")
  }
)

参考

https://github.com/onevcat/Kingfisher/issues/227
https://github.com/onevcat/Kingfisher/issues/94
Kingfisher Reference

16
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
17