Home > Software engineering >  Access to my API data outside its function
Access to my API data outside its function

Time:12-13

I have an API of list of countries and I'm trying to get access to the data fetched from the API outside its function.

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    @IBOutlet weak var tableView: UITableView!
    var apiData:[Countries] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        fetchAPI()
    }
    
    func fetchAPI() {
        let apiEndPoint = "https://restcountries.com/v2/all"
        
        guard let url = URL(string: apiEndPoint) else {
            print("Could not convert API endpoint to url object")
            return
        }
        
        URLSession.shared.dataTask(with: url) { (data,response, error) in
            if let err = error {
                print("Error occured while fetching the data")
                print(err)
                return
            }
            
            if let jsonData = data {
                do {
                    let decoder = JSONDecoder()
                    
                    let decodedItem:[Countries] = try decoder.decode([Countries].self, from: jsonData)
                    
                    DispatchQueue.main.async {
                        self.apiData = decodedItem
                    }
                } catch let error {
                    print("An error occured during JSON decoding")
                    print(error)
                }
            }
        }.resume()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as UITableViewCell
        return cell
    }
}

I tried defining an apiData variable outside the scope and passing the data to it but when I try to use it in my tableView it is empty.

What am I doing wrong?

CodePudding user response:

Assuming that no error occurs in your fetchAPI function, after getting response and passing the data to your apiData variable, you should reload tableView data:

self.tableView.reloadData()

And in numberOfRowsInSection function:

return apiData.count

Then you should configure each cell to show your data inside cellForRowAt function.

  • Related