gpt4 book ai didi

api - Swift 4 tableView API 分页

转载 作者:行者123 更新时间:2023-12-04 15:52:09 32 4
gpt4 key购买 nike

我已成功解析和解码 JSON 数据,它显示在控制台中。我不知道如何使用 api 设置分页并在 tableView 上向下滚动时显示所有数据。我使用的 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, pages: 25, next: "https://rickandmortyapi.com/api/character/?page=2", prev: ""), results: [API_Practice.PagedCharacters.Results(name: "Rick Sanchez", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Morty Smith", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Summer Smith", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Beth Smith", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Jerry Smith", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Abadango Cluster Princess", status: "Alive", species: "Alien"), API_Practice.PagedCharacters.Results(name: "Abradolf Lincler", status: "unknown", species: "Human"), API_Practice.PagedCharacters.Results(name: "Adjudicator Rick", status: "Dead", species: "Human"), API_Practice.PagedCharacters.Results(name: "Agency Director", status: "Dead", species: "Human"), API_Practice.PagedCharacters.Results(name: "Alan Rails", status: "Dead", species: "Human"), API_Practice.PagedCharacters.Results(name: "Albert Einstein", status: "Dead", species: "Human"), API_Practice.PagedCharacters.Results(name: "Alexander", status: "Dead", species: "Human"), API_Practice.PagedCharacters.Results(name: "Alien Googah", status: "unknown", species: "Alien"), API_Practice.PagedCharacters.Results(name: "Alien Morty", status: "unknown", species: "Alien"), API_Practice.PagedCharacters.Results(name: "Alien Rick", status: "unknown", species: "Alien"), API_Practice.PagedCharacters.Results(name: "Amish Cyborg", status: "Dead", species: "Alien"), API_Practice.PagedCharacters.Results(name: "Annie", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Antenna Morty", status: "Alive", species: "Human"), API_Practice.PagedCharacters.Results(name: "Antenna Rick", status: "unknown", species: "Human"), API_Practice.PagedCharacters.Results(name: "Ants in my Eyes Johnson", status: "unknown", species: "Human")])

如果您还需要什么,请告诉我。谢谢!

最佳答案

你的逻辑有很多缺陷,所以我重写了它,改动很小。现在它将为您服务。

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
}

下面是 View Controller 类的代码:

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

关于api - Swift 4 tableView API 分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53438239/

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