LoginSignup
31
32

More than 5 years have passed since last update.

SwiftでUIImageViewにURLから非同期で画像を取得してセットする(キャッシュ付き,URLSession)

Last updated at Posted at 2016-10-22

タイトル通り、URLから非同期で画像を取ってきて、完了後に自動で画像表示してくれるUIImageViewです。

AlamofireImageのサンプルやiOS10で非推奨のURLConnectionを使ったサンプルしか見つからなかったので、URLSessionを使って自作しました。

使い方

先に使い方から載せておきます。UIImageViewの代わりに使います。

let imageView = AsyncImageView(frame: CGRect(x: 0, y: 0, width: 40, height: 40));
imageView.loadImage("https://~~~/image.png");
self.view.addSubview(imageView);

loadImageメソッドはいつ呼んでもOKです。

Swift3.0用

AsyncImageView.swift
import UIKit
class SimpleAsyncImageView: UIImageView {
    let CACHE_SEC : TimeInterval = 5 * 60; //5分キャッシュ

    //画像を非同期で読み込む
    func loadImage(urlString: String){
        let req = URLRequest(url: NSURL(string:urlString)! as URL,
                               cachePolicy: .returnCacheDataElseLoad,
                               timeoutInterval: CACHE_SEC);
        let conf =  URLSessionConfiguration.default;
        let session = URLSession(configuration: conf, delegate: nil, delegateQueue: OperationQueue.main);

        session.dataTask(with: req, completionHandler:
            { (data, resp, err) in
                if((err) == nil){ //Success
                    let image = UIImage(data:data!)
                    self.image = image;

                }else{ //Error
                    print("AsyncImageView:Error \(err?.localizedDescription)");
                }
        }).resume();
    }
}

Swift2.3用

AsyncImageView.swift
import UIKit

class AsyncImageView: UIImageView {
    let CACHE_SEC : NSTimeInterval = 5 * 60;

    //画像を非同期で読み込む
    func loadImage(urlString: String){
        let req = NSURLRequest(URL: NSURL(string:urlString)!,
                               cachePolicy: .ReturnCacheDataElseLoad,
                               timeoutInterval: CACHE_SEC);
        let conf =  NSURLSessionConfiguration.defaultSessionConfiguration();
        let session = NSURLSession(configuration: conf, delegate: nil, delegateQueue: NSOperationQueue.mainQueue());

        session.dataTaskWithRequest(req, completionHandler:
            { (data, resp, err) in
                if((err) == nil){ //Success
                    let image = UIImage(data:data!)
                    self.image = image;

                }else{ //Error
                    print("AsyncImageView:Error \(err?.localizedDescription)");
                }
        }).resume();
    }
}

ちょっとしたデモ用なので、最低限画像を取得して表示する機能のみです。
失敗した時のNoImageや読み込み完了までのPlaceHolder画像などはカスタマイズしてお使いください〜

31
32
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
31
32