UICollectionView. Load List of Images From Remote Server Url

In this Swift code example, you will learn how to programmatically create UICollectionView and load a list of images from a remote URL. 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 the user taps on one of the collection view items
  • Create HTTP GET Request to load a list of images from server-side URL. A list of images will be loaded as a 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 the main application remains responsive while images are being loaded from a server
  • Add UIImageView as a 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

Complete Code Example

import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    
    var images = [AnyObject]()
    
    var myCollectionView:UICollectionView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        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
        self.view.addSubview(myCollectionView!)
        
        loadListOfImages()
    }
    
    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 = UIView.ContentMode.scaleAspectFit
                
                myCell.addSubview(imageView)
            }
        }
        
        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
            {
                print("error=\(String(describing: error))")
                return
            }
            
            // 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 {
                        self.myCollectionView!.reloadData()
                    }
                    
                }
            } catch let error as NSError {
                print(error.localizedDescription)
            }
            
        }
        
        task.resume()
    }
    
    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.


Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!