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() {
        super.viewDidLoad()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        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
                self.view.addSubview(imageView)      
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.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


Learn iOS Development with these Video Courses


How to Make a Freaking iPhone App - iOS 10 and Swift 3
icon icon


iOS 10 & Swift 3: From Beginner to Paid Professional
icon


The Complete iOS 10 Developer Course - Build 21 Apps
icon


Swift 3 - Learn to Code with Apple's New Language
icon icon


Learn How to Build Mobile Apps for iOS with Swift, PHP and MySQL
icon icon

Follow me on one of your favourite social networks to learn about new video tutorials and code examples:

Twitter: @SwiftVideoBlog
Google Plus: https://plus.google.com/+SergeyKargopolov/posts
Facebook: Swift Developer Blog on Facebook