在Swift中对电影数据库进行分页处理

4

我在使用MovieDB API的Swift应用程序中设置分页遇到了麻烦。通常,您需要设置一个限制和偏移量,然后将其传递给模型数组.count-1,这通常适用于CollectionView。但是,我正在使用Diffable数据源,无法找到解决方案。是否有人成功实现了这个或类似的操作?

当前API服务的样式如下所示:

  class APIService {

      static let shared = APIService()

    //always pass in your first API so the one which holds title, release date ect
    func fetchMovies(completionHandler: @escaping ([Movie]?, Error?) -> ()) {

        guard let url = URL(string: APINOWPLAYING) else {
            print("not a valid url")
            return
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let data = data {//when Decoding use the 2nd API model with the array 
                if let decodedResponse = try? JSONDecoder().decode(Movies.self, from: data) {

                    DispatchQueue.main.async {
                        completionHandler(decodedResponse.results, nil)
                        print("TOTAL RESULTS \(decodedResponse.page)")
                    }
                    return
                }
            }
            print("Fatch Failed \(error?.localizedDescription ?? "error unknown")")
        }.resume()

    }

视图控制器

  private func setupDiffableDataSource() {
        collectionView.dataSource = diffDataSource

        //MARK:- SetupHeader under Compositional Sections Extension
        setupHeader()

        APIService.shared.fetchMovies { (movies, err) in

            APIService.shared.fetchTopMovies { (movieGroup, err) in

                var snapshot = self.diffDataSource.snapshot()
                snapshot.appendSections([.topSection])
                snapshot.appendItems(movies ?? [], toSection: .topSection)

                snapshot.appendSections([.bottomSection])
                let objects = movieGroup?.results ?? []
                snapshot.appendItems(objects, toSection: .bottomSection)

                self.diffDataSource.apply(snapshot)
            }
        }
    }

有人知道如何使用API进行分页吗?

这是MOVIEDB API的调用示例:

let APINOWPLAYING = "https://api.themoviedb.org/3/movie/now_playing?api_key=(APIKEY)&language=en-US&page=1&total_pages=56"

希望有人能指点我正确的方向。

谢谢。

1个回答

7

你可以使用来自UICollectionViewDelegatefunc collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)

你需要更新你的服务,使其能够处理页面参数

var isCanLoadMore = false
var currentPage = 1

private func fetchData(page: Int) {
    // your API request
    // remember to change isCanLoadMore = true after apply(snapshot)
}

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    
    if isCanLoadMore {
        if diffableDataSource.snapshot().numberOfSections - 1 == indexPath.section {
            let currentSection = diffableDataSource.snapshot().sectionIdentifiers[indexPath.section]
            if diffableDataSource.snapshot().numberOfItems(inSection: currentSection) - 1 == indexPath.row {
                isCanLoadMore = false
                currentPage += 1
                print("NEXT PAGE")
                fetchData(page: currentPage)
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接