我尝试用URLSession.shared.dataTaskPublisher
更新UITableView
,第一次它按预期工作,但第二次当我尝试获取更多项时,值永远不会达到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=%5C(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()
}
}
2条答案
按热度按时间dzjeubhm1#
我认为您没有更新
currentPage
,因此它将获取相同的分页结果集。我认为在
self?.showsTableView.reloadData()
之后但在闭包结束之前递增此值。6bc51xsx2#
使用diffable tableview的快照会自动更新,值得的麻烦,因为最好的作品与合并。