如何在找到页面的最后一项时从下一页加载更多数据

How to Load More Data from next page when last item of the page found

我有更多页面的数据响应,目前它正在加载只有 20 条记录的第 1 页。

当我调用 Api 时,我将页码设为 1,如下所示。

 func getMovies()
    {
        API.getNewMovies(page: 1, completion: {movies in
            self.nowPlayingMovies = movies
            self.tableView.reloadData()
        })
    }

但是我想把页码做成动态的,根据页码加载更多的数据。

我知道如何检测数据到达最后一行的时间。但是到达后我想增加页面编号并加载下一页的更多数据以及现有数据。

我试过如下..但我知道这是错误的并且没有完全起作用。

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        // Check if the last row number is the same as the last current data element
        if indexPath.row == self.nowPlayingMovies.count - 1 {
            var pageNum:Int = 1
            pageNum += 1
            print(pageNum)
           // self.loadMore()
        }
    }

 func loadMore()
    {
      print("lastItem Reached")
         // let lastItem = nowPlayingMovies.last!
        //  print("lastItem \(lastItem)")
        // What Should I write here to load more data along with current data 
    }

我的数据模型

import Foundation

struct APIResults: Decodable {
    let page: Int
    let numResults: Int
    let numPages: Int
    let movies: [Movie]

    private enum CodingKeys: String, CodingKey {
        case page, numResults = "total_results", numPages = "total_pages", movies  = "results"
    }
}

struct Movie: Decodable  {
    let id:Int!
    let posterPath: String
    var videoPath: String?
    let backdrop: String
    let title: String
    var releaseDate: String
    var rating: Double
    let overview: String

    private enum CodingKeys: String, CodingKey {
        case id, posterPath = "poster_path", videoPath, backdrop = "backdrop_path", title, releaseDate = "release_date", rating = "vote_average", overview
    }
}

我正在使用数据模型。请用一些清晰的代码片段向我解释一下。

如果您需要更多代码来解释,请告诉我。我将 post 所需的代码。谢谢。

将 pageNumber 作为参数传递并将电影附加到您的数据源。

var lastPageRetrieved: Int
var nowPlayingMovies: [Movie] = []
var atTheEnd: Bool = false

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    // Check if the last row number is the same as the last current data element
    if indexPath.row == self.nowPlayingMovies.count - 1 {
        // Last item reach, load the next page if we're not at the end
        if !atTheEnd {
            self.loadMore()
        }
    }
}

func loadMore() {
    // Get the next page number
    var nextPage: Int = 1
    if lastPageRetrieved > 0 {
        nextPage += lastPageRetrieved
    }

    // Call the API with the right page number
    getMovies(page: nextPage)
}

func getMovies(page: Int) {
    API.getNewMovies(page: page, completion: {movies in

        guard let movies = movies else {
            // The movies were not loaded, are we at the end?  You can make this even
            //   smarter by checking the number of records in the page and if the records
            //   are less than the max page size, we'll know this is the last page
            self.atTheEnd = true
            return
        }

        // Append the new movies to the data source
        self.nowPlayingMovies += movies

        // Record the last page you retrieved
        self.lastPageRetrieved = page

        // Reload your tableView with the new movies
        self.tableView.reloadData()
    })
}

您需要存储上次检索的页面,并在获取页面数据后进行设置。此外,当 API 无法 return 或您已到达最后一页时,请考虑错误处理。

更新:我将代码编辑得更健壮了。

像下面给出的那样使用

    func loadMore()
        {
          print("lastItem Reached")
          let startingPageIndex = self.nowPlayingMovies.count + 1 // get the index
          getMoview(startingPageIndex: startingPageIndex) // call load movies api
        }

    func getMovies(startingPageIndex: Int) {
            API.getNewMovies(page: startingPageIndex, completion: {movies in
            if self.nowPlayingMovies.count > 0 {
            self.nowPlayingMovies += movies
            } else {
              self.nowPlayingMovies = movies
            }
            self.tableView.reloadData()
            })
        }