Paginating API results in SwiftUI requires managing data fetched from the API, and handling the UI to only display a subset of that data at a time. Here’s an example of how to implement pagination for an API using SwiftUI.
struct ContentView: View {
@State private var items: [Item] = []
@State private var isLoading = false
@State private var currentPage = 1
private let pageSize = 10
var body: some View {
ScrollView {
VStack {
ForEach(items) { item in
Text(item.name)
}
if isLoading {
ProgressView()
.onAppear(perform: loadMore)
}
}
}
.onAppear(perform: loadMore)
.navigationTitle("Paginated API Results")
}
func loadMore() {
guard !isLoading else { return }
isLoading = true
let url = URL(string: "https://example.com/api/items?page=\(currentPage)&size=\(pageSize)")!
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
let newItems = try! JSONDecoder().decode([Item].self, from: data)
DispatchQueue.main.async {
self.items.append(contentsOf: newItems)
self.currentPage += 1
self.isLoading = false
}
}
}.resume()
}
}
struct Item: Decodable, Identifiable {
var id: Int
var name: String
}
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?