UIImageView and UIImage. Load Image From Remote URL.

In this Swift code example we will learn how to create UIImageView programmatically and how to load an image from a remote url.

  • Create UIImageView and UIImage programmatically
  • Load image data from a remote url
  • Learn how to use dispatch_get_global_queue to start a background thread
  • Learn how to use dispatch_get_main_queue to update UI when background thread completes
  • Add UIImageView as subview to main view
  • Position UIImageView at the centre of UIView
    import UIKit
  class ViewController: UIViewController {
    override func viewDidLoad() {
    override func viewWillAppear(_ animated: Bool) {
        let imageUrlString = "http://swiftdeveloperblog.com/wp-content/uploads/2015/07/1.jpeg"
        let imageUrl:URL = URL(string: imageUrlString)!
        // Start background thread so that image loading does not make app unresponsive
         DispatchQueue.global(qos: .userInitiated).async {
            let imageData:NSData = NSData(contentsOf: imageUrl)!
            let imageView = UIImageView(frame: CGRect(x:0, y:0, width:200, height:200))
            imageView.center = self.view.center
            // When from background thread, UI needs to be updated on main_queue
           DispatchQueue.main.async {
                let image = UIImage(data: imageData as Data)
                imageView.image = image
                imageView.contentMode = UIViewContentMode.scaleAspectFit
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

Create an Image With Rounded Corners in Swift

Check out this code example that demonstrates how to create an Image with rounded corners.

Make UIImage Corners Rounded

[raw_html_snippet id=”cookbookpagecoursesheader”]

Unit Testing Swift Mobile App

Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.