In this Swift code example, you 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 the background thread completes,
- Add UIImageView as a subview to the main view,
- Position UIImageView at the center 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 = UIView.ContentMode.scaleAspectFit self.view.addSubview(imageView) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.