When working with paginated API responses in Swift, it's essential to handle the data correctly to ensure a smooth user experience. Pagination typically involves requesting a set number of records and then using pagination tokens or page numbers to fetch additional sets of records as needed.
Here's a basic example of how you can decode a paginated API response in Swift. This example uses the `Codable` protocol and demonstrates how to manage pagination effectively.
struct PaginatedResponse: Codable {
let data: [T]
let nextPage: String?
}
struct Item: Codable {
let id: Int
let name: String
}
func fetchItems(page: String? = nil, completion: @escaping ([Item]) -> Void) {
var urlString = "https://api.example.com/items"
if let page = page {
urlString += "?page=\(page)"
}
guard let url = URL(string: urlString) else { return }
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print("Error fetching data: \(String(describing: error))")
return
}
do {
let paginatedResponse = try JSONDecoder().decode(PaginatedResponse- .self, from: data)
completion(paginatedResponse.data)
} catch {
print("Failed to decode JSON: \(error)")
}
}
task.resume()
}
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?