Help with paged API and tableview with pagination

I'm trying to get the data from an API and display all of it in a tableview. So far I am able to parse the data and display only the first page of the data, but can't get the rest of the data from the other pages. How would I go about getting the data from the other pages of the API and then have the rest display as I am scrolling through the tableview? Here is my code so far.

import UIKit

struct Characters: Codable {
    let info: Info
    let results: [Result]
}

struct Info: Codable {
    let count, pages: Int
    let next: String
    let prev: String
}

struct Result: Codable {
    let name, status, species, gender: String
}

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {

    @IBOutlet var uiTableView: UITableView!
    var characters = [Result]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        getRickAndMortyData()
        
        
        self.uiTableView.dataSource = self
        self.uiTableView.delegate = self

    }

    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 rickAndMortyData = try JSONDecoder().decode(Characters.self, from: data)
                self.characters = rickAndMortyData.results
                DispatchQueue.main.async {
                    self.uiTableView.reloadData()
                }
                
            } catch {
                print(error)
                
            }
            
            }.resume()
        
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return characters.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "rickandmortyCell") as? CharacterTableViewCell else { return UITableViewCell() }
        
        cell.nameLabel.text = "Name: " + characters[indexPath.row].name
        
        return cell
    }
}
Terms of Service

Privacy Policy

Cookie Policy