Help us understand the problem. What is going on with this article?

[iOS] 画像を非同期で読み込む

More than 1 year has passed since last update.

画像の読み込み

URLから画像を読み込み、完了した時点で画面に反映させたい場合があるとします。この場合、画像のロードは非同期で行い、完了した時点でメインスレッドにてUIの操作を行う方法が考えられます。

URLSessionを用いて画像を読み込み、完了時にClosure内の処理を実行する
class ImageLoader {
    func loadImage(url: URL, completion: @escaping (_ succeeded: Bool, _ image: UIImage?) -> Void) {
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let data = data {
                completion(true, UIImage(data: data))
            }
        }.resume()
    }
}

使用例

ImageLoader().loadImage(url: imageUrl) { (succeeded, image) in
    if (succeeded) {
        DispatchQueue.main.async {
            self.imageView.image = image
        }
    }
}

注意点

UIの操作(ImageViewの更新)をバックグラウンドで行うと遅延やクラッシュの原因となるため、メインスレッドで行うようにしてください。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away