How do I implement pagination in a REST client in Swift?

Pagination is an essential feature in applications that display large amounts of data. It allows users to navigate through pages of data efficiently rather than loading all entries at once. In a REST client in Swift, you can implement pagination by requesting a specific subset of resources on each API call.

Example Implementation

Below is an example of how to implement pagination in a REST client in Swift using URL sessions to fetch paginated data:

import Foundation struct Item: Codable { let id: Int let name: String } class APIClient { let baseURL = "https://api.example.com/items" var currentPage = 1 let itemsPerPage = 10 func fetchItems(completion: @escaping ([Item]) -> Void) { guard let url = URL(string: "\(baseURL)?page=\(currentPage)&limit=\(itemsPerPage)") else { return } let task = URLSession.shared.dataTask(with: url) { data, response, error in guard let data = data, error == nil else { return } do { let items = try JSONDecoder().decode([Item].self, from: data) completion(items) } catch { print("Failed to decode JSON: \(error)") } } task.resume() } func loadNextPage(completion: @escaping ([Item]) -> Void) { currentPage += 1 fetchItems(completion: completion) } }

pagination REST client Swift API URLSession