I'm new to Swift development, I want to fetch data from API, and found some problems, I want to fetch 20 data only in my table view, and when I scroll to the bottom I can fetch another 20 data so on...
My problem here is this API directly response 220 data at once, I don't know how to separate into 20 and re-fetch
I have try some tutorial using cellWillDisplay and scrollViewDidScroll, but I can barely understand since they all use fixed data, Do someone know how to solve this?
here's my code, Model
func getBotanicalResults(pagination: Bool = false, completionHandler: @escaping (Result<[ResultsDetail], BotanicalError>) -> Void) {
let urlString = "https://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=f18de02f-b6c9-47c0-8cda-50efad621c14"
guard let url = URL(string: urlString) else {
completionHandler(.failure(.invalidURL))
return
}
let decoder = JSONDecoder()
URLSession.shared.dataTask(with: url) { data, response, error in
guard let jsonData = data else {
completionHandler(.failure(.noDataAvailable))
return
}
do {
let botanicalResponse = try decoder.decode(BotanicalMain.self, from: jsonData)
let botanicalResults = botanicalResponse.result.results
print("success getting results!")
completionHandler(.success(botanicalResults))
} catch {
completionHandler(.failure(.canNotProcessData))
}
}.resume()
}
here's my code, fetchData()
func fetchData() {
model.getBotanicalResults(pagination: false) { [weak self] result in
switch result {
case .failure(let error):
print(error)
case .success(let botanicals):
self?.listOfBotanical = botanicals
DispatchQueue.main.async {
self?.tableView.reloadData()
}
}
}
}
here's my code, cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: PropertyKeys.reuseIdentifier, for: indexPath) as? BotanicalCell else {
fatalError("Fail to dequeue BotanicalCell")
}
let botanical = listOfBotanical[indexPath.row]
cell.displayDetails(botanical)
return cell
}