简体   繁体   中英

API call does not work for the second time with combine

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=%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()
        }
     }

Use diffable tableview with snapshots which will update automatically, worth the hassle as works best with combine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM