gpt4 book ai didi

ios - 快速分页电影数据库

转载 作者:行者123 更新时间:2023-12-01 15:41:09 24 4
gpt4 key购买 nike

我无法使用 MovieDB API 快速设置分页
通常你会有一个限制和一个offet然后将中继到你的模型数组.count -1
使用 CollectionViews 时
我正在使用可区分的数据源,但看不到解决方案
有没有人设法实现这个或类似的东西?

当前的 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()

}

View Controller
  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"



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

谢谢

最佳答案

您可以使用 func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath)来自 UICollectionViewDelegate您需要更新您的服务,以便它可以处理页面参数

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)
}
}
}
}

关于ios - 快速分页电影数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61098095/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com