Pagination in UICollectionView with Swift 5

Pagination in UICollectionView with Swift 5
March 9, 2021 No Comments Development Pushpendra Kumar

Hey, Guys welcome to this tutorial. Here, I will make you understand the quick trick for how you can implement pagination in UICollectionView with Swift 5. And this is a simple way to achieve our goals. Through this simple tutorial. you can learn more interesting things about Pagination in UICollectionView with Swift 5. 

Pagination in swift

Infinite scroll is one of the basic requirements of the modern apps. It is a design pattern where content is continually load into the interface as the user scrolls downwards. Also called endless scroll, the point is that the user never reaches the end of the page. Instead they are present with a perpetual content stream without having to click or spend cognitive load on paginated navigation.

So, At the very first you have to understand the output of your server. Here, I would like to let you know that the output of the API. For reference please check the below output. Video Tutorial –

Pagination in UICollectionView Controller

Take a quick look into json.

{
    "status": 1,
    "message": "Success request.",
    "total_page": 4,
    "data": [
    {
        "id": "1",
        "name": "Maruti Swift"
        "company_name": "Maruti Suzuki"
    },
    {
        "id": "2",
        "name": "Maruti Swift"
        "company_name": "Maruti Suzuki"
    },
    {
        "id": "3",
        "name": "Maruti Swift"
        "company_name": "Maruti Suzuki"
    },
    {
        "id": "4",
        "name": "Maruti Swift"
        "company_name": "Maruti Suzuki"
        "vehicle_type": "Convertible"
    },
    {
        "id": "5",
        "name": "Maruti Swift"
        "company_name": "Maruti Suzuki"
    },
    {
        "id": "6",
        "name": "Maruti Swift"
        "company_name": "Maruti Suzuki"
    },
    {
        "id": "7",
        "name": "Benz E-Class",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "8",
        "name": "Z4",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "9",
        "name": "Benz SLC",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "10",
        "name": "Porsche 718",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "11",
        "name": "Porsche 911",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "12",
        "name": "Benz S-Class Cabriolet",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "13",
        "name": "Benz AMG GT",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "14",
        "name": "Maserati Gran Cabrio",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "15",
        "name": "Jaguar F Type",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "16",
        "name": "California T",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "17",
        "name": "Huracan",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "18",
        "name": "Continental",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "19",
        "name": "Aventador",
        "company_name": "Mercedes Ben"
    },
    {
        "id": "20",
        "name": "Rolls Royce Dawn",
        "company_name": "Mercedes Ben"
    }]
}

Cool, Now In Addition, let’s look on the swift code. 

//
//  PaginationCollectionViewController.swift
//  TableViewController
//
//  Created by Pushpendra on 09/03/21.
//  Copyright © 2021 Pushpendra. All rights reserved.
//

import UIKit


class PaginationCollectionViewController: UICollectionViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        fetchData(page: 1)
    }
    
    
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cars.count
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if current_page < total_page && indexPath.row == cars.count - 1 {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "loading_cell", for: indexPath) as! PaginationCollectionViewCell
            cell.actIndicator.startAnimating()

            return cell
        }else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! PaginationCollectionViewCell
            cell.lbTitle.text = cars[indexPath.row].company_name
            cell.lbDescription.text = cars[indexPath.row].engine_power
            return cell
        }
    }
    
    override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if current_page < total_page && indexPath.row == cars.count - 1 {
            current_page = current_page + 1
            DispatchQueue.main.asyncAfter(deadline: .now() + 10) {
                self.fetchData(page: self.current_page)
            }
        }
    }
    
    var total_page = 1
    var current_page = 1
    var cars : [Cars] = [Cars]()
    private func fetchData(page : Int, refresh : Bool = false){
        
        guard let url = URL(string: API.URL) else {
            return
        }
        let params = "page=\(page)&type=Car"
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = params.data(using: .utf8)
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            DispatchQueue.main.async {
                if refresh {
                    self.cars.removeAll()
                }
                if error != nil {
                    print(error.debugDescription)
                    return
                }else if data != nil {
                    do {
                        let myData = try JSONDecoder().decode(APIResponse<[Cars]>.self, from: data!)
                        if myData.status == 1 {
                            print("Current Page = \(self.current_page)")
                            self.total_page = myData.total_page ?? 1
                            self.cars.append(contentsOf: myData.data!)
                            self.collectionView.reloadData()
                        }
                    }catch let error {
                        print(error.localizedDescription)
                    }
                }
            }
        }
        task.resume()
    }
}

 

It’s completed 😊😊😊😊😊

In Conclusion, You have done with this tutorial. And I hope now the concept of Pagination in UICollectionView with Swift 5 is clear. Firstly, If you have any doubts regarding the Pagination in UICollectionView with Swift 5. Then you can comment into the comment box. And If you like this tutorial with a complete description of the simple and attractive tutorial in iOS then please like my video on YouTube and do not forget to subscribe to my YouTube channel. Because you will get lots of videos related to iOS development with very sort tricks.

In addition, If you are more curious about the development and knowing about tutorials then follow the below links 

Tags
About The Author
Pushpendra Kumar I am passionate about mobile application development and professional developer at Colour Moon Technologies Pvt Ltd (www.thecolourmoon.com). This website I have made so that I can meet with new challenges and can share here.

Leave a reply

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