我已经成功解析并解码了JSON数据,并显示在控制台中。我不知道当我向下滚动tableView时如何设置api的分页并显示所有数据。我使用的API是https://rickandmortyapi.com/api/character/。谢谢您提前提供的所有帮助!
这是我的主ViewController中的代码
import UIKit
struct PagedCharacters: Codable {
struct Info: Codable {
let count: Int
let pages: Int
let next: String
let prev: String
}
struct Results: Codable {
let name: String
let status: String
let species: String
}
let info: Info
let results: [Results]
}
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var uiTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
getRickAndMortyData()
self.uiTableView.dataSource = self
self.uiTableView.delegate = self
// Do any additional setup after loading the view.
}
func getRickAndMortyData() {
//create instance of the url
let url = "https://rickandmortyapi.com/api/character/"
//construct the url, use guard to avoid nonoptional
guard let urlObj = URL(string: url) else
{ return }
//fetch data
URLSession.shared.dataTask(with: urlObj) {(data, response, error) in
//to avoid non optional in JSONDecoder
guard let data = data else { return }
do {
//decode object
let downloadedRickAndMorty = try JSONDecoder().decode(PagedCharacters.self, from: data)
DispatchQueue.main.async {
self.uiTableView.reloadData()
}
print(downloadedRickAndMorty)
} catch {
print(error)
}
}.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "rickandmortyCell") as? CharacterTableViewCell else { return UITableViewCell() }
cell.nameLabel.text = "Name: " + PagedCharacters.Results[indexPath.row].name
return cell
}
}
这是我的tableviewcell类
import UIKit
class CharacterTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
这是打印解析的数据时我在控制台中获取的数据。我仍然无法从不同页面获取所有数据。
PagedCharacters(info:API_Practice.PagedCharacters.Info(count:493, 页数:25,下一页:“ https://rickandmortyapi.com/api/character/?page=2”, 上一个:“”),结果:[API_Practice.PagedCharacters.Results(名称:“ Rick 桑切斯”,状态:“活着”,物种:“人类”), API_Practice.PagedCharacters.Results(name:“ Morty Smith”,状态: “ Alive”,种类:“ Human”),API_Practice.PagedCharacters.Results(名称: “ Summer Smith”,状态:“活着”,种类:“人类”), API_Practice.PagedCharacters.Results(name:“ Beth Smith”,状态: “ Alive”,种类:“ Human”),API_Practice.PagedCharacters.Results(名称: “杰里·史密斯”,状态:“还活着”,物种:“人类”), API_Practice.PagedCharacters.Results(name:“ Abadango群集 公主”,状态:“活着”,物种:“外星人”), API_Practice.PagedCharacters.Results(name:“ Abradolf Lincler”,状态: “未知”,种类:“人类”), API_Practice.PagedCharacters.Results(name:“ Adjudicator Rick”,状态: “ Dead”,种类:“ Human”),API_Practice.PagedCharacters.Results(名称: “代理总监”,状态:“死亡”,种类:“人类”), API_Practice.PagedCharacters.Results(name:“ Alan Rails”,状态: “ Dead”,种类:“ Human”),API_Practice.PagedCharacters.Results(名称: “爱因斯坦(Albert Einstein)”,状态:“死亡”,物种:“人类”), API_Practice.PagedCharacters.Results(name:“ Alexander”,状态: “ Dead”,种类:“ Human”),API_Practice.PagedCharacters.Results(名称: “ Alien Googah”,状态:“未知”,种类:“ Alien”), API_Practice.PagedCharacters.Results(name:“ Alien Morty”,状态: “未知”,种类:“外星人”), API_Practice.PagedCharacters.Results(name:“ Alien Rick”,状态: “未知”,种类:“外星人”), API_Practice.PagedCharacters.Results(name:“ Amish Cyborg”,状态: “ Dead”,种类:“ Alien”),API_Practice.PagedCharacters.Results(名称: “ Annie”,状态:“活着”,物种:“人类”), API_Practice.PagedCharacters.Results(名称:“天线莫蒂”,状态: “ Alive”,种类:“ Human”),API_Practice.PagedCharacters.Results(名称: “ Antenna Rick”,状态:“未知”,种类:“人类”), API_Practice.PagedCharacters.Results(name:“ Ants in My Eyes Johnson”, 状态:“未知”,种类:“人类”)))
如果您还有其他需要,请告诉我。谢谢!
答案 0 :(得分:1)
您的逻辑中有许多缺陷,因此我以最小的更改将其重写。现在它将满足您的目的。
import UIKit
struct PagedCharacters: Codable {
let info: Info
let results: [Results]
}
struct Info: Codable {
let count: Int
let pages: Int
let next: String
let prev: String
}
struct Results: Codable {
let name: String
let status: String
let species: String
}
这是视图控制器类的代码:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var uiTableView: UITableView!
var aryDownloadedData:[Results]?
var nextPageUrl:String!
override func viewDidLoad() {
super.viewDidLoad()
getIntitalRickAndMortyData()
self.uiTableView.dataSource = self
self.uiTableView.delegate = self
// Do any additional setup after loading the view.
}
func getIntitalRickAndMortyData(){
aryDownloadedData = []
//here first page is next page
nextPageUrl = "https://rickandmortyapi.com/api/character/"
getRickAndMortyData()
}
func getRickAndMortyData() {
//construct the url, use guard to avoid nonoptional
guard let urlObj = URL(string: nextPageUrl) else
{ return }
//fetch data
URLSession.shared.dataTask(with: urlObj) {[weak self](data, response, error) in
//to avoid non optional in JSONDecoder
guard let data = data else { return }
do {
//decode object
let downloadedRickAndMorty = try JSONDecoder().decode(PagedCharacters.self, from: data)
self?.aryDownloadedData?.append(contentsOf: downloadedRickAndMorty.results)
self?.nextPageUrl = downloadedRickAndMorty.info.next
DispatchQueue.main.async {
self?.uiTableView.reloadData()
}
print(self?.aryDownloadedData as Any)
} catch {
print(error)
}
}.resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.aryDownloadedData?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let count = aryDownloadedData?.count, count>1{
let lastElement = count - 1
if indexPath.row == lastElement {
//call get api for next page
getRickAndMortyData()
}
}
guard let cell = tableView.dequeueReusableCell(withIdentifier: "rickandmortyCell") as? CharacterTableViewCell else { return UITableViewCell() }
cell.nameLabel.text = "Name: " + (self.aryDownloadedData?[indexPath.row].name ?? "default")
return cell
}
}