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)
}
}
}
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?