【问题标题】:Access to my API data outside its function在其功能之外访问我的 API 数据
【发布时间】:2022-01-16 08:34:46
【问题描述】:

我有一个国家/地区列表的 API,我正在尝试访问从 API 获取的数据,而不是其功能。

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

我尝试在作用域外定义一个apiData 变量并将数据传递给它,但是当我尝试在我的tableView 中使用它时,它是空的。

我做错了什么?

【问题讨论】:

    标签: ios swift api


    【解决方案1】:

    假设您的 fetchAPI 函数没有发生错误,在获得响应并将数据传递给您的 apiData 变量后,您应该重新加载 tableView 数据:

    self.tableView.reloadData()
    

    并且在 numberOfRowsInSection 函数中:

    return apiData.count
    

    然后您应该配置每个单元格以在 cellForRowAt 函数中显示您的数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2019-08-25
      • 2017-01-08
      • 1970-01-01
      • 2020-06-10
      • 2022-11-21
      • 1970-01-01
      相关资源
      最近更新 更多