I'm trying to update an UITableView
with URLSession.shared.dataTaskPublisher
the first time it works as expected but the second time when I try to fetch more items the values never gets to sink
.
private var filteredShows: Show?
private var currentPage : Int = 1
private var isLoadingList : Bool = false
private var cancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
fetchShows(currentPage)
}
private func fetchShows(_ pageNumber: Int) {
cancellable = ShowService().getShows(pageNumber: String(pageNumber)).map { [weak self] shows in
self?.isLoadingList = false
self?.filteredShows = shows
}.sink { _ in } receiveValue: { [weak self] _story in
self?.isLoadingList = false
self?.showsTableView.reloadData()
}
}
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
filteredShows?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell");
cell.textLabel?.text = filteredShows?[indexPath.row].name
return cell
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if (((scrollView.contentOffset.y scrollView.frame.size.height) > scrollView.contentSize.height ) && !isLoadingList) {
self.isLoadingList = true
self.loadMoreItemsForList()
}
}
}
class ShowService: RequestProtocol {
func getShows(pageNumber: String) -> AnyPublisher<Show, Error> {
guard let url = URL(string: "https://api.tvmaze.com/shows?page=\(pageNumber)") else { fatalError("wrong url") }
return URLSession.shared.dataTaskPublisher(for: url)
.receive(on: RunLoop.main)
.map( .data )
.decode(type: Show.self, decoder: JSONDecoder())
.catch { _ in Empty<Show, Error>() }
.eraseToAnyPublisher()
}
}
CodePudding user response:
I don't think you're updating currentPage
, so it will fetch the same paginated set of results.
I think increment this after self?.showsTableView.reloadData()
but before the closure ends.
CodePudding user response:
Use diffable tableview with snapshots which will update automatically, worth the hassle as works best with combine.