我在使用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"
希望有人能指点我正确的方向。
谢谢。