LoginSignup
91
91

More than 5 years have passed since last update.

Swiftで画像をURLから非同期で読み込む

Last updated at Posted at 2014-11-18

はじめに

UITableViewなどにネットワーク上の画像を表示する場合には、ユーザの操作をブロックしないように画像を非同期で読み込むのが普通だと思います。

筆者はSwiftではhttp系のライブラリとしてAlamofireを使っていますが、同じ作者がObjective-Cで書いたAFNetworkingとは異なり画像の非同期読み込みをまだサポートしていません。参考

Swiftで書く場合はライブラリもSwift製にしたいと思いますので、ここではiOS標準のNSURLConnectionを使って画像の非同期読み込みを記述してみます。

画像の非同期読み込み

let url = NSURL(string:"http://画像のURL")
let req = NSURLRequest(URL:url!)

NSURLConnection.sendAsynchronousRequest(req, queue:NSOperationQueue.mainQueue()){(res, data, err) in
    let image = UIImage(data:data)
    // 画像に対する処理 (UcellのUIImageViewに表示する等)
}

Swiftならこのようにシンプルに記述できます。

  • 型を省略してTrailing Closureを使って短く書いた例です。

  • エラー処理は省略しています。

91
91
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
91
91