画像(URL)をUIImageとして描画する方法 – Swift3

参考

Swift 3: Display Image from URL をコピペしただけですが

Swift3でサーバーにある画像(URL)をUIImageとして描画する方法

環境

-Swift3
-Xcode8

実装

まずはletで宣言した後に、URLのコンテンツをダウンロードする。これはURLSessionオブジェクトで行うことができる。補完ハンドラが呼び出されると、WebからUIImageがダウンロードされます。

let catPictureURL = URL(string: "https://i.imgur.com/w5rkSIj.jpg")!

// Creating a session object with the default configuration.
// You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
let session = URLSession(configuration: .default)

// Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
    // The download has finished.
    if let e = error {
        print("Error downloading cat picture: \(e)")
    } else {
        // No errors found.
        // It would be weird if we didn't have a response, so check for that too.
        if let res = response as? HTTPURLResponse {
            print("Downloaded cat picture with response code \(res.statusCode)")
            if let imageData = data {
                // Finally convert that Data into an image and do what you wish with it.
                let image = UIImage(data: imageData)
                // Do something with your image.
            } else {
                print("Couldn't get image: Image is nil")
            }
        } else {
            print("Couldn't get response code for some reason")
        }
    }
}

downloadPicTask.resume()

最後に、downloadPicTask.resume()で呼び出します。そうしないと、タスクは開始されません。このコードはすべて最初はちょっと気になるかもしれませんが、URLSession APIはブロックベースであり、非同期で動作することができます。UIスレッドを数秒間ブロックすると、OSがアプリケーションを終了します。

 //デフォルト設定でセッションオブジェクトを作成する。
        //ここで詳しく読むことができますhttps://developer.apple.com/reference/foundation/urlsessionconfiguration
        let catPictureURL = URL(string: String(describing: CastAnotherThemeList02[1][row]))!
        // Creating a session object with the default configuration.
        // You can read more about it here https://developer.apple.com/reference/foundation/urlsessionconfiguration
        let session = URLSession(configuration: .default)

        // Define a download task. The download task will download the contents of the URL as a Data object and then you can do what you wish with that data.
        let downloadPicTask = session.dataTask(with: catPictureURL) { (data, response, error) in
            // The download has finished.
            if let e = error {
                print("Error downloading cat picture: \(e)")
            } else {
                // No errors found.
                // It would be weird if we didn't have a response, so check for that too.
                if let res = response as? HTTPURLResponse {
                    print("Downloaded cat picture with response code \(res.statusCode)")
                    if let imageData = data {
                        // Finally convert that Data into an image and do what you wish with it.
                        let imageimage = UIImage(data: imageData)
                        print(imageimage!)
                        self.templateThumbnailImageView.image = imageimage
                        // Do something with your image.
                    } else {
                        print("Couldn't get image: Image is nil")
                    }
                } else {
                    print("Couldn't get response code for some reason")
                }
            }
        }

        downloadPicTask.resume()
藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事