Swift 4 tableView API分页 [英] Swift 4 tableView API Pagination

查看:71
本文介绍了Swift 4 tableView API分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功解析并解码了JSON数据,并显示在控制台中.我不知道如何在api上向下滚动时如何设置api的分页并显示所有数据.我使用的API是 https://rickandmortyapi.com/api/character/.谢谢您提前提供的所有帮助!

I have successfully parsed and decoded the JSON data and it displays in the console. I don't know how I would set up pagination with the api and display all of the data when I scroll down on the tableView. The API I'm using is https://rickandmortyapi.com/api/character/. Thank you for all your help in advance!

这是我的主ViewController中的代码

This is the code in my main 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类

This is my tableviewcell class

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
    }

}

这是打印解析的数据时我在控制台中获取的数据.我仍然无法从不同页面获取所有数据.

This is the data I'm getting in my console when the parsed data is printed. I'm still not getting all the data from the different pages.

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(名称:"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(名称: 安妮",状态:还活着",物种:人类"), API_Practice.PagedCharacters.Results(名称:天线莫蒂",状态: "Alive",种类:"Human"),API_Practice.PagedCharacters.Results(名称: "Antenna Rick",状态:未知",种类:人类"), API_Practice.PagedCharacters.Results(name:"Ants in My Eyes Johnson", 状态:未知",种类:人类")))

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")])

如果您还有其他需要,请告诉我.谢谢!

If you need anything else please let me know. Thank you!

推荐答案

您的逻辑中有很多缺陷,因此我以最小的更改将其重写.现在它将满足您的目的.

There were many flaws in your logic, so I have rewritten it with minimal changes. Now it will serve your purpose.

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
}

这是视图控制器类的代码:

And here is the code for view controller class:

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

这篇关于Swift 4 tableView API分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆