Below is my code. The print (currency) function works here. This means that json data is being retrieved. But it does not appear in the table view.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var TableData:Array< String > = Array < String >()
override func viewDidLoad()
{
super.viewDidLoad()
get_data_from_url("http://api.fixer.io/latest")
}
Table part
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return(TableData.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = TableData[indexPath.row]
return (cell)
}
Retrieving JSON Data
func get_data_from_url(_ link:String)
{
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let rates = myJson["rates"] as? NSDictionary
{
if let currency = rates["NOK"] as? String
{
print(currency)
self.TableData.append(currency)
self.tableView.reloadData()
}
}
}
catch
{
}
}
}
}
task.resume()
}
Data is displayed in xcode with print function. Therefore, it is clear that the data is retrieved. But the problem is loading the data into the table. Please help me download it.
source
share