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.
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)
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?