How do I paginate API results in UIKit with Swift?

Paginating API results in UIKit with Swift involves fetching a limited number of data entries at a time and loading more as the user scrolls. This is especially useful for enhancing performance and user experience when dealing with large datasets.

Below is an example of how to implement pagination when fetching data from an API in a Swift application using UIKit.

import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var items: [YourDataType] = [] var currentPage = 1 let itemsPerPage = 20 var isLoading = false @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self fetchData(page: currentPage) } func fetchData(page: Int) { guard !isLoading else { return } isLoading = true let urlString = "https://api.example.com/data?page=\(page)&limit=\(itemsPerPage)" guard let url = URL(string: urlString) else { return } URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, error == nil else { self.isLoading = false return } do { let newItems = try JSONDecoder().decode([YourDataType].self, from: data) self.items.append(contentsOf: newItems) DispatchQueue.main.async { self.tableView.reloadData() self.isLoading = false } } catch { self.isLoading = false } }.resume() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = items[indexPath.row].name // Replace '.name' with your data model property return cell } func scrollViewDidScroll(_ scrollView: UIScrollView) { let offsetY = scrollView.contentOffset.y let contentHeight = scrollView.contentSize.height if offsetY > contentHeight - scrollView.frame.size.height - 100 { currentPage += 1 fetchData(page: currentPage) } } }

pagination API Swift UIKit data loading scroll user experience