【发布时间】:2020-11-30 15:43:24
【问题描述】:
我正在使用 Youtube 数据 API 构建一个 iOS 应用程序,它获取频道的播放列表并将其显示在表格视图中。但问题是我最多只能获得 50 个播放列表结果。但播放列表的实际数量超过100.当我用谷歌搜索它时,我发现应该完成额外的结果分页。如何在 iOS 应用程序中添加分页以在表格视图中显示整个播放列表。如果我想使用 nextpage 令牌发出另一个请求,那么应该如何我做了它,应该修改代码的哪一部分。我使用 API 密钥而不是 OAuth
ViewController 代码
import UIKit
class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var coursesTV: UITableView!
var a = [Item]()
override func viewDidLoad() {
super.viewDidLoad()
coursesTV.delegate = self
coursesTV.dataSource = self
Playlist.sharedObj.getPlayList { (i) in
self.a = i
DispatchQueue.main.async {
self.coursesTV.reloadData()
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return a.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
{
cell.textLabel?.text = a[indexPath.row].snippet!.title!
return cell
}
return UITableViewCell()
}
}
网络服务结构
import Foundation
public struct Playlist
{
public static let sharedObj = Playlist()
let playlistuRL = "URL_HERE"
let session = URLSession(configuration: .default)
func getPlayList(onSuccess:@escaping([Item])-> Void)
{
let task = self.session.dataTask(with: URL(string: self.playlistuRL)!) { (data, response, error) in
do
{
let item = try JSONDecoder().decode(RootClass.self, from: data!)
print(item.items!.first!.snippet!.title!)
onSuccess(item.items)
}
catch
{
print(error)
}
}
task.resume()
}
}
模型结构
import Foundation
public struct RootClass: Codable {
public var etag : String!
public var items : [Item]!
public var kind : String!
public var nextPageToken : String!
public var pageInfo : PageInfo!
}
public struct Default: Codable {
public var height : Int!
public var url : String!
public var width : Int!
}
public struct High: Codable {
public var height : Int!
public var url : String!
public var width : Int!
}
public struct Item: Codable {
public var etag : String!
public var id : String!
public var kind : String!
public var snippet : Snippet!
}
public struct Localized: Codable {
public var descriptionField : String!
public var title : String!
}
public struct Medium: Codable {
public var height : Int!
public var url : String!
public var width : Int!
}
public struct PageInfo: Codable {
public var resultsPerPage : Int!
public var totalResults : Int!
}
public struct Snippet: Codable {
public var channelId : String!
public var channelTitle : String!
public var descriptionField : String!
public var localized : Localized!
public var publishedAt : String!
public var thumbnails : Thumbnail!
public var title : String!
}
public struct Standard: Codable {
public var height : Int!
public var url : String!
public var width : Int!
}
public struct Thumbnail: Codable {
public var defaultField : Default!
public var high : High!
public var medium : Medium!
public var standard : Standard!
}
【问题讨论】:
标签: ios swift youtube-api