UICollectionView. Load List of Images From Remote Server Url

In this Swift code example we will learn how to programmatically create UICollectionView and load list of images from server side php script. The below swift code example will cover

  • Create UICollectionView programmatically
  • Set UICollectionView item size(width and height)
  • Set UICollectionView background color
  • Set UICollectionView Item background color
  • Implement UICollectionView Delegate method didSelectItemAtIndexPath to handle an event when user taps on one of the collection view items
  • Create HTTP GET Request to load list of images from server side url. List of images will be loaded as JSON array of JSON objects from http://swiftdeveloperblog.com/list-of-images/.
  • Create UIImageView
  • Create UIImageData and load image from a remote URL
  • Load images in a background thread so that main application remains responsive while images are being loaded from server
  • Add UIImageView as subview to UICollectionViewCell
  • Learn how to scale loaded image properly so that it nicely fits into image view size by setting image view content mode to UIViewContentMode.ScaleAspectFit
      import UIKit

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    var images = [AnyObject]()
    var myCollectionView:UICollectionView?
    override func viewDidLoad() {
    override func viewWillAppear(_ animated: Bool) {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
        layout.itemSize = CGSize(width: 60, height: 60)
        myCollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
        myCollectionView!.dataSource = self
        myCollectionView!.delegate = self
        myCollectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell")
        myCollectionView!.backgroundColor = UIColor.white
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.images.count
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath as IndexPath)
        myCell.backgroundColor = UIColor.black
        let imageDictionary = self.images[indexPath.row] as! NSDictionary
        let imageUrlString = imageDictionary.object(forKey: "thumb") as! String
        let imageUrl:NSURL = NSURL(string: imageUrlString)!
       DispatchQueue.global(qos: .userInitiated).async {
            let imageData:NSData = NSData(contentsOf: imageUrl as URL)!
        let imageView = UIImageView(frame: CGRect(x:0, y:0, width:myCell.frame.size.width, height:myCell.frame.size.height))
            DispatchQueue.main.async {
                let image = UIImage(data: imageData as Data)
                imageView.image = image
                imageView.contentMode = UIViewContentMode.scaleAspectFit
        return myCell
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
        print("User tapped on item \(indexPath.row)")
        let imageDictionary = self.images[indexPath.row] as! NSDictionary
        let imageUrlString = imageDictionary.object(forKey: "thumb") as! String
        print("Image url = \(imageUrlString)")
    func loadListOfImages()
        // Send HTTP GET Request
        // Define server side script URL
        let scriptUrl = "http://swiftdeveloperblog.com/list-of-images/"
        // Add one parameter just to avoid caching
        let urlWithParams = scriptUrl + "?UUID=\(NSUUID().uuidString)"
        // Create NSURL Ibject
        let myUrl = URL(string: urlWithParams);
        // Creaste URL Request
        var request = URLRequest(url:myUrl!)
        // Set request HTTP method to GET. It could be POST as well
        request.httpMethod = "GET"
        // Excute HTTP Request
        let task = URLSession.shared.dataTask(with: request) {
            data, response, error in
            // Check for error
            if error != nil
            // Convert server json response to NSDictionary
            do {
                if let convertedJsonIntoArray = try JSONSerialization.jsonObject(with: data!, options: []) as? NSArray {
                    self.images = convertedJsonIntoArray as [AnyObject]
                    DispatchQueue.main.async {
            } catch let error as NSError {
    override func didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

Video Tutorial on How to Create UICollectionView Using Storyboard and How To Load Images From Remote URL

Watch this video tutorial to learn more about UICollectionView. In this video tutorial you will learn:

  • How to create UICollectionView using Storyboard
  • Implement custom UICollectionViewCell
  • Load list of images by calling a server side PHP script which will return a JSON array of images
  • Display images in UIScrollView
  • When user taps on an image, open image in a separate view controller

UICollectionView example in Swift

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

The Complete iOS 10 Developer Course - Build 21 Apps

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