Loading an Image Asynchronously
Download image from Internet using URLSession and its dataTask method. Image will be loaded asynchronously and set as image of UIImageView in main UI thread using DispatchQueue.main.async.
Display downloaded image
import UIKit class SingleImageViewController: UIViewController { @IBOutlet var imageView: UIImageView! let urlStr = "https://cdn.pixabay.com/photo/2017/05/07/08/56/pancakes-2291908_960_720.jpg" override func viewDidLoad() { super.viewDidLoad() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true if let url = URL(string: urlStr) { let session = URLSession.shared let dataTask = session.dataTask(with: url) { (data, response, error) in if let unwrappedError = error { print(unwrappedError) return } if let unwrappedData = data { let image = UIImage(data: unwrappedData) DispatchQueue.main.async(execute: { self.imageView.image = image }) } } dataTask.resume() } } }