参考
Swift 3: Display Image from URL をコピペしただけですが
Swift3でサーバーにある画像(URL)をUIImageとして描画する方法
環境
-Swift3
-Xcode8
実装
まずはlet
で宣言した後に、URL
のコンテンツをダウンロードする。これはURLSession
オブジェクトで行うことができる。補完ハンドラが呼び出されると、Web
からUIImage
がダウンロードされます。
let catPictureURL = URL(string: "http://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()