0

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...

API here

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
}
  • "to fetch 20 data" You mean, 20 records? No person can count data. – El Tomato Oct 03 '21 at 07:21
  • So where is your cellWillDisplay or scrollViewDidScroll thing? – El Tomato Oct 03 '21 at 07:23
  • Have you looked at prefetchDataSource: https://developer.apple.com/documentation/uikit/uitableview/1771763-prefetchdatasource – Rob C Oct 03 '21 at 07:27
  • @ElTomato yes, 20 records, I just see their is so many way for pagination, but not sure whether they can fit my code, but after using limit & offset parameter in the API, I can just limit my data fetching in 20 and load another 20 after I scroll to the bottom, all those are wrote in tableView datasource cellForRowAt! – Krauser Huang Oct 04 '21 at 08:15

2 Answers2

0

The API you mentioned should have limit, offset, etc parameters. If the api does not have such arguments, you can not have those pagination logic. If api supports that you can check the sample project below. The main page has a pagination logic uses what you want to create.

sampleproject

erkutbas
  • 305
  • 2
  • 9
0

Welcome to Swift!

First: API parameter queries

You have this api:

https://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=f18de02f-b6c9-47c0-8cda-50efad621c14

It supports limit and offset parameter query. So, how to add them? You should add them after ?

P.S: limit is the number of records and offset is the number of skipped records.

For example: This will return 1 record and starting from the beginning.

https://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=f18de02f-b6c9-47c0-8cda-50efad621c14&limit=1&offset=0

And, This will return 20 record and starting from the beginning (Same as: Page 1).

https://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=f18de02f-b6c9-47c0-8cda-50efad621c14&limit=20&offset=0

Finally, This will return 20 record and starting from the next 20 records (Same as: Page 2).

https://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=f18de02f-b6c9-47c0-8cda-50efad621c14&limit=20&offset=20

Second: Load more rows when user reach the end of table view:

Load more technique to allow table view paging

Hamad Fuad
  • 266
  • 3
  • 12
  • How do you know all this stuff? Do you work for data.taipei? – El Tomato Oct 03 '21 at 11:49
  • @ElTomato No, it is straightforward because I have experience :) – Hamad Fuad Oct 03 '21 at 12:08
  • @HamadFuad thanks for the suggestion! I have tried that on postman before and it does have limit and offset parameter. – Krauser Huang Oct 04 '21 at 08:09
  • I'm just too dumb to solve how to fetch another 20 data, I think load more need to have offset parameter, and after the cell is scroll to the last cell, I need to call loadMore() and append the data into my previous array, I just solve it XD – Krauser Huang Oct 04 '21 at 08:10
  • but need to add some indicator to show loading, I think loadMore() behavior is faster than I think :) – Krauser Huang Oct 04 '21 at 08:12