为什么此网络呼叫不返回图像

时间:2017-12-04 11:29:26

标签: ios network-programming uiimage swift-playground

如果我将此URL放入浏览器,则206 KB图像会在2秒后返回。 为什么这个电话没有完成下载? 返回的数据有响应200,我认为这意味着http调用已经完成。

//: Playground - noun: a place where people can play

import UIKit
import PlaygroundSupport

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)

func getImageFromURL(_ imageURL: String, completion: @escaping (UIImage?) -> Void) {
  if let url = URL(string: imageURL) {
    print("Download: \(imageURL)")
    let urlRequest = URLRequest(url: url, timeoutInterval: 29.0)

    session.dataTask(with: urlRequest) { (data: Data?, response: URLResponse?, error: Error?) -> Void in
      guard let response = response, let data = data else {
        completion(nil)
        print("Failed to load image.")
        return
      }

      print("Image data is \(data)")
      let downloadedImage = UIImage(data: data)
      DispatchQueue.main.async {
        completion(downloadedImage)
        print("Downloaded image size: \(downloadedImage?.size)")
      }
    }.resume()
  }
}

PlaygroundPage.current.needsIndefiniteExecution = true
let theUrlString: String = "http://www.impawards.com/2014/posters/american_sniper_xlg.jpg" // 206 KB image

var theImage: UIImage = UIImage()
getImageFromURL(theUrlString) { image in
  theImage = image!
}
print("theImage size: \(theImage.size)")

0 个答案:

没有答案